Share via

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 | Windows | Classic Outlook for Windows | For business
Microsoft 365 and Office | Install, redeem, activate | For business | Windows
Developer technologies | Visual Basic for Applications

1 answer

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

    Try calling OleInitialize( ) at the beginning of fn.

    Or call CoInitializeEx(NULL, COINIT_APARTMENTTHREADED).

    Was this answer helpful?


Your answer

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