我有超级简单的WinApi程序。关闭按钮不会破坏程序的进程。应该添加什么?
#include <windows.h>
#include <stdlib.h>
#include <string.h>
#include <tchar.h>
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
HINSTANCE hINSTANCE;
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpstr,
int nCmdShow) {
// VARIABLES
TCHAR className[] = _T("win32api");
TCHAR windowName[] = _T("Protected Window");
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(NULL, IDI_INFORMATION);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)COLOR_BACKGROUND;
wcex.lpszMenuName = NULL;
wcex.lpszClassName = className;
wcex.hIconSm = LoadIcon(NULL, IDI_SHIELD);
if (!RegisterClassEx(&wcex)) {
MessageBox(NULL, _T("Cannot register window"), _T("Error"), MB_OK | MB_ICONERROR);
return 0;
}
HWND hWnd = CreateWindow(className,
windowName,
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
300,
300,
NULL,
NULL,
hInstance,
NULL);
if (!hWnd) {
MessageBox(hWnd, _T("Call to register windows isn't working"), _T("Error"), NULL);
return 1;
}
hINSTANCE = hInstance;
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
MSG msg;
while (GetMessage(&msg, hWnd, 0, 0) != 0 || GetMessage(&msg, hWnd, 0, 0) != -1) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int)msg.lParam;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT uInt, WPARAM wParam, LPARAM lParam) {
PAINTSTRUCT ps;
HDC hdc;
switch (uInt) {
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
TextOut(hdc, 10, 20, _T("Text sample right here boyz."), _tcsclen(_T("Text sample right here boyz.")));
EndPaint(hWnd, &ps);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, uInt, wParam, lParam);
break;
}
return 0;
}
如果再加上一种情况
case WM_CLOSE:
PostQuitMessage(0);
break;
它根本不会关闭(按关闭按钮没有做任何事情)。任何其他提示都非常感谢。
最佳答案
您的消息循环是错误的,原因有两个:
您两次拨打GetMessage()
。不要那样做!想想如果发生的话会发生什么。如果GetMessage()
左侧的||
调用检测到WM_QUIT
(它不能,请参见下文),它将返回0。这将导致||
调用右侧,忽略上一个调用中的GetMessage()
并阻塞循环,直到稍后收到新消息。您应该在每个循环迭代中仅调用一次WM_QUIT
,然后根据需要对返回值进行操作:
BOOL bRet;
do
{
bRet = GetMessage(&msg, hWnd, 0, 0);
if (bRet == 0) break;
if (bRet == -1)
{
// handle the error and possibly exit
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
while (1);
但是,您还按
GetMessage()
(don't do that!)筛选邮件,因此它将仅返回通过HWND
发布到指定HWND
的邮件。 PostMessage()
将其PostQuitMessage()
消息发布到调用线程本身的输入队列,而不发布到WM_QUIT
。因此,筛选将永远不会看到HWND
消息。为了使WM_QUIT
中断循环,您需要完全停止通过WM_QUIT
进行过滤,或者至少定期进行未过滤的调用。您的消息循环应该看起来像这样。这是标准的消息循环:
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
在这种情况下,请注意there is no need to handle -1 from
HWND
!。关于c++ - WinApi任务查杀,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36871265/