My program will sometimes be launched from another program. If that’s the case, I want to be able to send messages back and forth between the two programs using WM_COPYDATA.
After my child program launches, how can it get the HWND for the calling program? Is there a function I can call to do it, or can I do it indirectly, e.g. get the process ID of the calling program and then go from that to an HWND?
Thanks.
There’s a slight problem involved. A single calling program can have multiple HWND’s, from multiple windows. And no, I’m afraid there isn’t a way to get the calling program’s PID or something similar. There is no way to get the “parent” process of your process, at least in Windows. You can’t do anything without knowing the name of the calling function, then you can look up it’s PID and get a list of its active windows.
I suggest working backwards, passing the calling process’s HWND as a command line parameter to your program. e.g. “start YourProgram.exe /hwnd:1234”
EDIT: I just found out that there IS a way, but just not supplied by Windows. http://www.codeproject.com/KB/threads/ParentPID.aspx . But there is a caveat. PIDs are generated and recycled constantly, so if you do get the PID, no guarentee its parent isn’t dead (crash or ended process) and the PID being used by something else. Then interacting with the supposed parent process will become highly dangerous and instable. So yes, you can do it. But be careful, if the parent crashes, and you attempt to access it via its old PID, you’ll be running into major problems, particularly if you accidentally inject something into, say, the Windows service host.