C++ problem accessing ms office interop API from background thread

Shabari Pragash 126 Reputation points
2022-07-07T21:24:30.05+00:00

MS Office interop API working when called within the class containing Addin OnConnection method. But when i call the same API from another thread, it fails with some unknown exception.

Read in few forum pages that Office automation is Single-threaded.

Any way to override this behaviour? Few people in few forums mentioned about using IMessageFilter, but i can't figure it out about using it in C++.

Please guide. Here is some sample code.

CComQIPtr<Word::_Application> pWordApp;  
CComQIPtr<Word::Windows> spWindows;  
  
DWORD WINAPI fn(LPVOID lpParam)  
{  
          pWordApp->get_Windows(&spWindows);  //////// not working, some exception is raised  
}  
  
class ATL_NO_VTABLE CConnect :  
{  
public:  
STDMETHOD(OnConnection)(LPDISPATCH Application, ext_ConnectMode ConnectMode, LPDISPATCH AddInInst, SAFEARRAY** custom)  
{  
pWordApp = Application;  
  
pWordApp->get_Windows(&spWindows); ////// working  
  
CreateThread(NULL, 0, fn, NULL, 0, NULL);  
}  
  
}  
Outlook Management
Outlook Management
Outlook: A family of Microsoft email and calendar products.Management: The act or process of organizing, handling, directing or controlling something.
5,501 questions
Office Management
Office Management
Office: A suite of Microsoft productivity software that supports common business tasks, including word processing, email, presentations, and data management and analysis.Management: The act or process of organizing, handling, directing or controlling something.
2,284 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 120K Reputation points
    2022-07-08T06:16:18.89+00:00

    Try calling OleInitialize( ) at the beginning of fn.

    Or call CoInitializeEx(NULL, COINIT_APARTMENTTHREADED).


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.