Using sendmessage to send wm_close to another process

I want to send wm_close to another process that I want to end this process with safely.

int _tmain(int argc, _TCHAR* argv[]) { DWORD SetOfPID; SetOfPID = GetProcId(_T("abc.exe")); //this will return pid HANDLE h = OpenProcess(PROCESS_ALL_ACCESS,false, SetOfPID); HWND hwnd = ::GetTopWindow(NULL); while(hwnd) { DWORD pid; DWORD dwThreadId = ::GetWindowThreadProcessId(hwnd, &pid); if(pid == SetOfPID) { break; } hwnd = ::GetNextWindow(hwnd, GW_HWNDNEXT); } //DestroyWindow(hwnd); bool temp = IsWindow(hwnd); **//this gives true** LRESULT res = ::SendMessage(hwnd, WM_CLOSE, NULL, NULL); DWORD err = GetLastError(); **//this gives 6** CloseHandle(hwnd); CloseHandle(h); return 0; } 

this piece of code looks good, but the target process does not end, can someone help me?

+1
source share
3 answers

Are you sure the window you find is correct? With Spy ++ you can easily check. Moreover, when searching for a window, I find it better to use EnumWindows. I'm not sure your method is correct.

+1
source

If the application does not process WM_CLOSE, then DefWindowProc should handle this (gracefully closing the application), however, if the application processes WM_CLOSE, then it can simply ignore it. Try sending WM_DESTROY and WM_NCDESTROY messages.

0
source

I would try to close the window (process c) in the following order:

  • WM_CLOSE

  • WM_QUIT

  • WM_DESTROY

  • TerminateProcess ().

Just take how I process ( WM_CLOSE off) WM_CLOSE for a window and with difficulty distinguish between the "Close and close" messages sent by another main task. WM_QUIT seems to solve my problem without using my own WM_APP_CLOSE . TerminateProcess is, in extreme cases, an unclean output that should be avoided at all costs (it can leave descriptors (e.g. COM, etc.), as well as memory, etc.).

0
source

All Articles