英文:
How to close app when mouse click outside the window?
问题
我正在创建一个Win32
单窗口应用程序。我想要的是当用户单击应用窗口外部的任何地方时,应用程序会关闭。
我曾经在某处看到,可以通过处理WM_KILLFOCUS
消息来实现这一点。但似乎不起作用(甚至没有接收到WM_KILLFOCUS
消息!)。
以下是我的消息循环的代码部分:
LRESULT CALLBACK WndProc(HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam) {
HDC hdc;
PAINTSTRUCT ps;
switch (message) {
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
OnPaint(hdc);
EndPaint(hWnd, &ps);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_COMMAND: {
switch (LOWORD(wParam)) {
case WM_KILLFOCUS:
MessageBoxA(NULL, "焦点将被移除", "WM_KILLFOCUS", MB_OK);
DestroyWindow(hWnd);
return TRUE;
}
}
...
}
}
英文:
I'm creating a Win32
single window application. What I want is the application to close when the user clicks anywhere outside the app window.
I've read somewhere that to do that one can handle the WM_KILLFOCUS
message. But that does not seems to work (the WM_KILLFOCUS
is't even received!).
Here is the code of my message loop:
LRESULT CALLBACK WndProc(HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam) {
HDC hdc;
PAINTSTRUCT ps;
switch (message) {
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
OnPaint(hdc);
EndPaint(hWnd, &ps);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_COMMAND: {
switch (LOWORD(wParam)) {
case WM_KILLFOCUS:
MessageBoxA(NULL, "Focus will be gone", "WM_KILLFOCUS", MB_OK);
DestroyWindow(hWnd);
return TRUE;
}
}
...
}
}
答案1
得分: 1
正如在回答问题检查窗口是否失去焦点中所述,您可以监听WM_ACTIVATE消息,因为它
> 发送给正在激活的窗口和正在停用的窗口。
但我认为这不是Windows应用程序的正确行为方式。有时候,您的应用程序可能会因为其他原因失去焦点,而不是用户点击别处,而且他们可能还不想退出应用程序。在我看来,您似乎正在尝试重新创建网站对话框提供的交互,其中单击其外部可以关闭对话框。
> 当应用程序遵循Windows样式和标准的Windows行为时,用户无需重新学习交互模式。
如果您在失去焦点时关闭应用程序,我认为可能会让用户感到困惑。
英文:
As described in an answer to the question Check if window is losing focus you could listen for the WM_ACTIVATE message as it is
> Sent to both the window being activated and the window being deactivated.
But I don't think this is how an Windows application should behave. There are going to be times when your application loses focus for reasons other than the user clicking somewhere else and they may not have wanted to exit the application yet. It seems to me you are trying to recreate the interaction provided by website dialog boxes, where clicking outside of them can close the dialog.
The Windows Application Development - Best Practices for User Experience recommends
> When applications adhere to Windows styles and standard Windows behaviors, users don't have to re-learn interaction patterns.
I think you may confuse users if you close the application when it loses focus.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论