C++ 使用 sendmessage 将 wm_close 发送到另一个进程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5402158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
using sendmessage to send wm_close to another process
提问by rplusg
I want to send wm_close to another process, with which i want end that process safely.
我想将 wm_close 发送到另一个进程,我想安全地结束该进程。
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 doesn't terminate, can somebody help me?
这段代码看起来不错,但目标进程没有终止,有人可以帮助我吗?
采纳答案by pagra
Are you sure that the window you are finding is the correct one? You can check easily with Spy++. Moreover, when searching for a window, I think it's better to use EnumWindows. I'm not sure your method is correct.
您确定您找到的窗口是正确的吗?您可以使用 Spy++ 轻松检查。而且,在搜索窗口时,我认为最好使用EnumWindows。我不确定你的方法是否正确。
回答by mattjs
I would attempt to close a (Process with) Window(s) in the following order:
我将尝试按以下顺序关闭(处理)窗口:
WM_CLOSE
WM_QUIT
WM_DESTROY
TerminateProcess().
WM_CLOSE
WM_退出
WM_DESTROY
终止进程()。
Just my take as I am handling (disabling) WM_CLOSE
for a Window and having difficulty distinguishing between User Close and close messages send by another master task. WM_QUIT
seems to resolve my problem without using a custom WM_APP_CLOSE
of my own. TerminateProcess
is very much a last resort unclean exit to be avoided at all costs (it may leave handles (e.g. COM etc) and memory etc unfreed).
只是我在处理(禁用)WM_CLOSE
窗口并且难以区分由另一个主任务发送的用户关闭和关闭消息时的看法。WM_QUIT
似乎在不使用WM_APP_CLOSE
我自己的习惯的情况下解决了我的问题。TerminateProcess
是不惜一切代价避免不干净退出的最后手段(它可能会留下句柄(例如 COM 等)和内存等未释放)。
回答by Ferenc Deak
If the application does not process WM_CLOSE the DefWindowProc should handle this (by gracefully closing the application), however if the application is handling WM_CLOSE then it simply can choose to ignore it. Try sending the WM_DESTROY and WM_NCDESTROY messagees instead.
如果应用程序不处理 WM_CLOSE,DefWindowProc 应该处理这个(通过正常关闭应用程序),但是如果应用程序正在处理 WM_CLOSE,那么它可以选择忽略它。尝试改为发送 WM_DESTROY 和 WM_NCDESTROY 消息。