Reputation: 13908
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.
Upvotes: 1
Views: 903
Reputation: 941555
WM_COPYDATA is a pretty miserable way to interop, given the need to find a valid window handle. Nevertheless, nothing useful is going to happen unless that other program is actively cooperating with yours, it is going to dump the WM_COPYDATA message in the garbage can otherwise. Since that program already needs to know a lot about yours, including where to find it and handling the message, it might also simply provide you with a command line argument that contains what you need.
Yes, the window handle could be passed as a command line argument, you'll get it from main() or GetCommandLine() in the child process.
Consider a named pipe or a socket as a better mousetrap. Or out-of-process COM.
Upvotes: 2
Reputation: 308206
Have the very first message sent by the launching program be its HWND so that the child knows who to send to.
Upvotes: 2
Reputation: 1744
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.
Upvotes: 3