delphicomapartmentsapartment-state

How to get the main thread of a console app to be MTA?


With Delphi, how can I create a (Windows) console application that has a main thread that is initialized as COINIT_MULTITHREADED?

If I call CoInitializeEx(nil, COINIT_MULTITHREADED) in the very first statement, I get a HRESULT 0x80010106 (Cannot change thread mode after it is set), so obviously some previously running code already called CoInitialize/Ex.

How can I get the main thread to be COINIT_MULTITHREADED?


Solution

  • One of the units included in your program as a result of your uses clause has already initialized COM in its unit initialization section.

    You need to identify that unit, and remove it from your program.

    Consider this program:

    {$APPTYPE CONSOLE}
    
    uses
      ActiveX,
      ComObj;
    
    begin
      Writeln(CoInitializeEx(nil, COINIT_MULTITHREADED));
    end.
    

    The output is 0 which demonstrates that an empty console application does not initialize COM.