注册 登录
编程论坛 C图形专区

Win32 WM_PAINT消息

seahdiao 发布于 2020-12-30 10:56, 3093 次点击
为什么窗口会一直闪烁换颜色?我没有移动窗口,也没有调整大小,他还是一直响应WM_PAINT消息。请问怎样才能把他改成当你移动他或换大小才改变颜色,感谢大佬。

程序代码:

#include<Windows.h>
#include<d2d1.h>
#include"dx.h"

LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM);

dx* graphic;

int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,PSTR szCmdLine,int iCmdShow) {

    HWND hwnd;
    MSG msg = { 0 };
    WNDCLASS wndclass;
    TCHAR className[] = TEXT("HELLO WORLD !");

    wndclass.hInstance = hInstance;
    wndclass.lpszClassName = className;
    wndclass.style = CS_HREDRAW | CS_VREDRAW;
    wndclass.lpfnWndProc = WndProc;
    wndclass.hCursor = nullptr;
    wndclass.hIcon = nullptr;
    wndclass.cbClsExtra = 0;
    wndclass.cbWndExtra = 0;
    wndclass.hbrBackground = nullptr;
    wndclass.lpszMenuName = NULL;

    if (!RegisterClass(&wndclass)) {
        MessageBox(NULL, TEXT("REGISTER ERROR"), className, MB_OK);
        return 0;
    }
   
   
    hwnd = CreateWindow(
        className,
        TEXT("Hello World!"),
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT,
        1280, 720,
        NULL,
        NULL,
        hInstance,
        NULL
    );

    if (hwnd == NULL) {
        MessageBox(NULL, TEXT("Create Window Error"), className, MB_OK);
        return 0;
    }
   
    graphic = new dx();

    if (!graphic->Init(hwnd)) {
        delete graphic;
        return -1;
    }

    ShowWindow(hwnd, iCmdShow);
    UpdateWindow(hwnd);

    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    delete graphic;

   
    return msg.wParam;

}

LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {


    switch (message) {
    case WM_PAINT:
        graphic->renderTarget->BeginDraw();
        graphic->renderTarget->Clear(D2D1::ColorF(rand()%100/100.0f, rand() % 100 / 100.0f, rand() % 100 / 100.0f));
        graphic->renderTarget->EndDraw();
        
        return 0;


    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
   

    }

    return DefWindowProc(hwnd, message, wParam, lParam);
}
4 回复
#2
apull2020-12-30 11:19
case WM_PAINT里不能直接这么写,要加个判断窗口移动或者大小改变。
而移动和大小改变则需要其他函数实现。
WM_MOVE,WM_SIZE这2个消息是移动和改变大小,在里面放置一个变量用到WM_PAINT里
#3
seahdiao2020-12-30 11:53
我这样写还是不能
程序代码:

case WM_PAINT:

        if (message == WM_MOVE||message==WM_SIZE) {
            graphic->renderTarget->BeginDraw();
            graphic->renderTarget->Clear(D2D1::ColorF(rand() % 100 / 100.0f, rand() % 100 / 100.0f, rand() % 100 / 100.0f));
            graphic->renderTarget->EndDraw();
        }
        
        return 0;
#4
apull2020-12-30 18:12
case WM_PAINT:里message==WM_PAINT,你的if不成,用变量吧。
#5
seahdiao2020-12-31 09:59
看不是很懂,用变量是什么意思?能否将那段代码敲出来
1