我正在编写类似于Windows中的“绘画”程序。首先,我尝试制作一个“铅笔”函数来处理WM_MOUSEMOVE消息并正确调用SetPixel()。但是,当鼠标移动得太快时,并不会出现所有像素(它们看起来很稀疏)。我想我必须用另一个代码替换该SetPixel()函数,但是我不知道是什么。

最佳答案

  • 在窗口上捕获WM_LBUTTONDOWNset capture,保存第一个鼠标坐标。
  • 捕获WM_MOUSEMOVE,并从第一个坐标到现在的坐标绘制。然后,将现在的坐标保存到第一个鼠标坐标中。
  • 重复2。
  • 捕获WM_LBUTTONUPrelease capture

  • 例:
    #include <windows.h>
    #include <windowsx.h>
    
    LRESULT CALLBACK WndProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam);
    
    int APIENTRY WinMain(HINSTANCE hInst, HINSTANCE, LPSTR, int)
    {
        WNDCLASS wc;
        HWND hWnd;
        MSG msg;
    
        wc.cbClsExtra = 0;
        wc.cbWndExtra = 0;
        wc.hInstance = hInst;
        wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
        wc.hCursor = LoadCursor(NULL, IDC_ARROW);
        wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
        wc.lpszMenuName = NULL;
        wc.lpszClassName = L"adf";
        wc.style = CS_HREDRAW | CS_VREDRAW;
        wc.lpfnWndProc = WndProc;
        RegisterClass(&wc);
    
        hWnd = CreateWindow(L"adf", NULL, WS_OVERLAPPEDWINDOW,
            CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
            NULL, NULL, hInst, NULL);
        ShowWindow(hWnd, SW_NORMAL);
    
        while (GetMessage(&msg, 0, 0, NULL))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        return (int)msg.wParam;
    }
    
    LRESULT CALLBACK WndProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam)
    {
        static int prevx, prevy;
    
        switch (iMsg)
        {
        case WM_LBUTTONDOWN:
            prevx = GET_X_LPARAM(lParam);
            prevy = GET_Y_LPARAM(lParam);
            SetCapture(hWnd);
            return 0;
        case WM_LBUTTONUP:
            ReleaseCapture();
            return 0;
        case WM_MOUSEMOVE:
            if (GetCapture() == hWnd)
            {
                HDC hdc = GetDC(hWnd);
                MoveToEx(hdc, prevx, prevy, NULL);
                LineTo(hdc, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
                prevx = GET_X_LPARAM(lParam);
                prevy = GET_Y_LPARAM(lParam);
                ReleaseDC(hWnd, hdc);
            }
            return 0;
        case WM_DESTROY:
            PostQuitMessage(0);
            return 0;
        }
        return DefWindowProc(hWnd, iMsg, wParam, lParam);
    }
    

    09-13 04:30