为什么鼠标点击窗口还是不能激活? 以下是一个最小的可重现示例:
#include <Windows.h>
#include <strsafe.h>
const int width = 800;
const int height = 600;
LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_MOUSEMOVE:
{
const POINTS pt = MAKEPOINTS(lParam);
// in client region -> log move, and log enter + capture mouse (if not previously in window)
if (pt.x >= 0 && pt.x < width && pt.y >= 0 && pt.y < height)
{
SetCapture(hWnd);
TCHAR buffer[256];
StringCchPrintf(buffer, 256, TEXT("xPos: %d, yPos: %d"), pt.x, pt.y);
SetWindowText(hWnd, buffer);
}
// not in client -> log move / maintain capture if button down
else
{
ReleaseCapture();
SetWindowText(hWnd, TEXT("OnMouseLeave"));
}
break;
}
case WM_LBUTTONDOWN:
{
SetWindowText(hWnd, TEXT("WM_LBUTTONDOWN"));
break;
}
case WM_RBUTTONDOWN:
{
SetWindowText(hWnd, TEXT("WM_RBUTTONDOWN"));
break;
}
case WM_LBUTTONUP:
{
SetWindowText(hWnd, TEXT("WM_LBUTTONUP"));
break;
}
case WM_RBUTTONUP:
{
SetWindowText(hWnd, TEXT("WM_RBUTTONUP"));
break;
}
case WM_CLOSE:
{
DestroyWindow(hWnd);
}
break;
case WM_DESTROY:
{
PostQuitMessage(0);
}
break;
default:
{
}
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
WNDCLASS wc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hInstance = hInstance;
wc.lpfnWndProc = WindowProc;
wc.lpszClassName = TEXT("main");
wc.lpszMenuName = NULL;
wc.style = CS_HREDRAW | CS_VREDRAW;
RegisterClass(&wc);
RECT wr;
wr.left = 100;
wr.right = width + wr.left;
wr.top = 100;
wr.bottom = height + wr.top;
if (AdjustWindowRect(&wr, WS_CAPTION | WS_MINIMIZEBOX | WS_SYSMENU, FALSE) == 0)
{
MessageBox(NULL, TEXT("Error"), TEXT("Error"), MB_OK);
}
HWND hWnd = CreateWindow(wc.lpszClassName, TEXT("Windows"), WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
wr.right - wr.left, wr.bottom - wr.top,
NULL, NULL, hInstance, NULL);
if (hWnd == NULL)
{
return 0;
}
ShowWindow(hWnd, SW_SHOWNORMAL);
UpdateWindow(hWnd);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
我运行程序时,窗口可以正常运行。当我单击另一个窗口时,主窗口变为非活动状态。当我再次点击主窗口时,主窗口无法激活。为什么?
我尝试评论 SetCapture(hWnd) 函数,效果很好。
if (pt.x >= 0 && pt.x < width && pt.y >= 0 && pt.y < height)
{
//SetCapture(hWnd);
TCHAR buffer[256];
StringCchPrintf(buffer, 256, TEXT("xPos: %d, yPos: %d"), pt.x, pt.y);
SetWindowText(hWnd, buffer);
}