笔颜色错误

时间:2013-12-29 15:18:48

标签: c++ visual-studio-2010 winapi

我尝试使用以下代码更改笔颜色:

redPen = CreatePen(PS_SOLID,1,0xFF0000); 
SelectObject(hdc, redPen);

但它从黑色变为蓝色。而且无论颜色是什么,因为如果我尝试设置新颜色,笔总是会是蓝色,如果我什么都不做,那么笔总是黑色 这是完整的代码:

#include "windows.h"

int N=50;
int M=30;
int X=25;

int width=X * N;
int height=X * M;

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

int WINAPI WinMain(HINSTANCE h,HINSTANCE hprevinstance,LPSTR lpcmdline,int ncmdshow){
    WNDCLASSEX wc;
    HWND hwnd;
    MSG msg;

    ZeroMemory(&msg,sizeof(MSG));
    wc.cbSize=sizeof(wc);
    wc.style=CS_OWNDC|CS_HREDRAW|CS_VREDRAW;
    wc.lpfnWndProc=WndProc;
    wc.cbClsExtra=0;
    wc.cbWndExtra=0;
    wc.hInstance=h;
    wc.hIcon=LoadIcon(NULL,IDI_APPLICATION);
    wc.hCursor=LoadCursor(h,IDC_ARROW);
    wc.hbrBackground=(HBRUSH)GetStockObject(GRAY_BRUSH);
    wc.lpszMenuName=NULL;
    wc.lpszClassName="main";
    wc.hIconSm=LoadIcon(NULL,IDI_APPLICATION);
    if(!RegisterClassEx(&wc)) return 0;

    if(!(hwnd=CreateWindowEx(NULL,"main","test",WS_OVERLAPPEDWINDOW|WS_VISIBLE,0,0,width,height,NULL,NULL,h,NULL))) return 0;

    ShowWindow(hwnd,SW_SHOWDEFAULT);
    UpdateWindow(hwnd);

    while(msg.message != WM_QUIT){
        if(PeekMessage(&msg,NULL,0,0,PM_REMOVE)){
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }
    return msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam){
      HDC hdc;
      PAINTSTRUCT ps;
    HPEN redPen;
    switch (message){
    case WM_PAINT:
      hdc = BeginPaint(hwnd, &ps);
      redPen = CreatePen(PS_SOLID,1,0xFF0000); 
      SelectObject(hdc, redPen);
      for(int i=0;i<width;i+=X){
        MoveToEx(hdc,i,0,NULL);
        LineTo(hdc,i,height);
      }
      for(int j=0;j<height;j+=X){
        MoveToEx(hdc,0,j,NULL);
        LineTo(hdc,width,j);
      }
      EndPaint(hwnd, &ps);
      return 0;

    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
    }
    return DefWindowProc(hwnd, message, wParam, lParam);
}

1 个答案:

答案 0 :(得分:8)

  redPen = CreatePen(PS_SOLID,1,0xFF0000); 

不,这绝对是错误的标识符名称,它应该是“bluePen”。 COLORREF以十六进制编码为0x00bbggrr。所以0x00ff0000是蓝色,而不是红色。

使用RGB宏代替成功:

  redPen = CreatePen(PS_SOLID, 1, RGB(0xFF, 0, 0));