August 26th, 2010

How do I recover the window handle passed to ShellExecute?

A customer had the following question:

I’m using the ShellExecute function to launch a new process and am passing the handle to my application’s main window as the hwnd parameter. From the new process, I want to get information from the old process, and to do that, I need the window handle. How can I recover that window handle from the new process?

You can’t. That window handle is used by the ShellExecute function only to host any user interface operations that occur as a result of the attempt to execute the program. For example, it is the owner window used for any error dialogs. The ShellExecute function does not pass the window handle to the launched process. (It couldn’t even if it wanted to: There is nowhere to pass it. There is no window handle among the parameters to CreateProcess nor is there a window handle in the STARTUPINFO structure.)

If you want to pass this information to the process being launched, you’ll have to come up with your own mechanism for transferring this information. For example, you can pass it on the command line, or if you have a lot of information to pass, you can use a shared memory block.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.