2

I made a custom control that needs to use API DoDragDrop function and they say I must call OleInitialize before calling this function.

I do that in MyControl.Create method but I get S_FALSE result, so it means that the COM library is already initialized. But who initialize it ?

I do not initialize this before in my application. I am thinking, maybe there is some delphi unit who initialize it in his initialization section... And a secondary question is what should I do, should I continue initializing the COM Library in MyControl.Create method or should I not initialize at all (because it's already initialized) ?

Toby Allen
  • 10,997
  • 11
  • 73
  • 124
Marus Gradinaru
  • 2,824
  • 1
  • 26
  • 55

1 Answers1

3

As stated in my answer to a similar question:

In the RTL/VCL source, COM is initialized in the following ways:

  1. By a call to OleInitialize made from Forms.TApplication.Create. So this call will be made for all VCL forms applications, but not, for example, for service applications.
  2. By a call to CoInitialize or CoInitializeEx in ComObj.InitComObj. This is registered as an InitProc in the initialization section of the ComObj unit. In turn, the call to Application.Initialize in your project .dpr file's code will invoke ComObj.InitComObj.
  3. In many and various other locations around the RTL/VCL. Including, but not limited to, Datasnap, ComServ, Soap, System.Win.Sensors, Winapi.DirectShow9. Some of these areas of code are more recent than Delphi 7.

Now, of these various COM initializations, the ones that count are 1 and 2. In any standard VCL forms application, both of these will run at startup in the main thread. Item 1 runs first and so gets to initialize COM first. That's the initialization that counts. Item 2 runs after and returns S_FALSE meaning that COM was already initialized.

All VCL applications include the Forms unit and so you can be sure thaat COM is initialized in the main VCL thread. For other threads you need to initialize COM if necessary.


You must never initialize COM in control or more generally a thread that you are not in control of. If you do so then your initialization may conflict with the apartment type specified by the owner of the thread.

Community
  • 1
  • 1
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • There is no check whether the `OleInitialize` call succeeded, so you cannot be sure until you call it by yourself. You can only hope. – TLama Jul 10 '15 at 13:53
  • @TLama if it failed then, it's going to fail again – David Heffernan Jul 10 '15 at 13:54
  • Not with the `OLE_E_WRONGCOMPOBJ` failure (if you would update those libraries and call it again). But the chances are less than you'll be hit by a falling piano. – TLama Jul 10 '15 at 14:00