Close another application

Hello again
What I want to do now is to close another opened application, without leaving dlls or other trash in memory. I understand that I have to send a WM_QUIT message to the handler of the other application. What I don't know is how do I get it (the hWnd)? Could you give me some clues? Thanks
I don't think you can send WM_QUIT directly, but since I have never done it I cannot tell for sure.

To find a particular window, you use FindWindow() or FindWindowEx(). I would first attempt to close it using a WM_CLOSE message.
So, FindWindow() can get windows of another application (instance), not the windows of the current one, isn't it?
Correct. Look up detailed information @ MSDN Online.
Here is something that works for me:

1. Use EnumProcesses() to get an array of all of the ProcessIDs.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682629(v=vs.85).aspx

2. For each ProcessID, use OpenProcess() to open and get a handle to each process. Use PROCESS_QUERY_INFORMATION | PROCESS_TERMINATE access rights. If the process doesn't open, then you don't have permission to close it, it's probably a system process.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms684320(v=vs.85).aspx

3. If the process has opened successfully, use GetModuleBaseName() to get the process' name.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms683196(v=VS.85).aspx

4. If the name matches, use TerminateProcess() to terminate the process.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686714(v=VS.85).aspx

I'm not sure how to do this in a more Win32 gui style with hWnd but I am pretty sure that if a process is terminated, all of the memory that was dedicated to that process is now free.
Last edited on
Thanks to everyone. Stewbond, I will use TerminateProcess, which is a more brutal than SendMessage(WM_CLOSE), only if SendMessage doesn't close the window. Thanks, again!
Beware that SendMessage and FindWindow is a blocking call. If one of the external app is hanging, your application will be blocked too.
True in the case of SendMessage() with WM_CLOSE, but FindWindow() will not block on hung windows. It has special treatment if I recall correctly.

You can replace SendMessage() with SendMessageTimeout(). If it times out, use TerminateProcess().
Topic archived. No new replies allowed.