强制调用WM_PAINT

Forcing the recall of WM_PAINT

本文关键字:PAINT WM 调用      更新时间:2023-10-16

我使用CreateWindowEx创建了一个窗口,它运行良好。窗口打开。

在我处理消息(特别是WM_PAINT(的函数中,我使用GetCursorPos获取光标位置,然后在那里绘制一个矩形。但是,我希望窗口像光标一样不断更新和重新绘制这个矩形。

我创建了一个像下面这样的线程来尝试并强制执行:

DWORD WINAPI RedrawLoop(LPVOID lpParam) {
HWND handle = (HWND)lpParam;
while (true) {
RECT lpRect;
GetClientRect(handle, &lpRect);
InvalidateRect(handle, &lpRect, TRUE);
UpdateWindow(handle);
}
return 0;
}

然而,这并不奏效。我已经检查了传入的句柄是否与线程外的窗口句柄相同。

我也尝试过连续发送SendMessage(handle, WM_PAINT, 0, 0);RedrawWindow(handle, NULL, NULL, 0);,但没有成功。

首先,您可以通过处理WM_MOUSEMOVE消息来获得当前光标位置,并使当前窗口无效。

然后通过WM_PAINT消息中的Rectangle函数绘制一个矩形。(注:坐标原点为屏幕左上角(

这是示例:

#include <Windows.h>
#include <commctrl.h>
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
static TCHAR szAppName[] = TEXT("hello windows");
HWND hwnd;
MSG msg;
WNDCLASS wndclass;
wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = szAppName;
if (!RegisterClass(&wndclass))
{
MessageBox(NULL, TEXT("This program requires Windows NT!"), szAppName, MB_ICONERROR);
}
hwnd = CreateWindow(szAppName,
TEXT("the hello program"),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
NULL,
NULL,
hInstance,
NULL);
ShowWindow(hwnd, iCmdShow);
UpdateWindow(hwnd);
while (GetMessageW(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
return msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
PAINTSTRUCT ps;
RECT rect;
static POINT pt;
switch (message)
{
case WM_CREATE:
{
}
case WM_MOUSEMOVE:
{
Sleep(100);
GetCursorPos(&pt);
InvalidateRect(hwnd, NULL, FALSE);
return 0;
}
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
GetClientRect(hwnd, &rect);
Rectangle(hdc, pt.x-rect.right/4 , pt.y-rect.bottom/4, pt.x + rect.right / 4, pt.y + rect.bottom / 4);
EndPaint(hwnd, &ps);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, message, wParam, lParam);
}