ShellExecuteEx and Coinitialize in VCL thread

左心房为你撑大大i 提交于 2019-12-19 08:12:32

问题


Do I need to call Coinitialize in the main/VCL thread in Delphi before using ShellExecuteEx?

For a thread, yes but for the VCL thread ?


回答1:


No need to call CoInitialize for Windows Forms Applications. This is done for you in the main thread. More specific TApplication.Create in Forms.Pas:

...
if not IsLibrary then
 FNeedToUninitialize := Succeeded(OleInitialize(nil));
...



回答2:


If in doubt, do it. In either case, CoInitialize() will return a hr : HRESULT which you should check, because you need to CoUninitialize() on SUCCEEDED(hr), but not when FAILED(hr). A failed result usually indicates that it already has been called.

Cited from your MSDN ref:

Nonetheless, it is good practice to always initalize COM before using this function.




回答3:


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.

So, to your question:

Do I need to call Coinitialize in the main/VCL thread?

No you do not. You can be sure that COM has already been initialized in a VCL application's main thread.



来源:https://stackoverflow.com/questions/19984807/shellexecuteex-and-coinitialize-in-vcl-thread

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!