如何在条件下打印位图?

时间:2014-03-21 09:45:35

标签: c++ winapi

请帮我按条件打印位图。 我有两个按钮创建为

    case WM_CREATE:
    HWND button1,button2;

    button1= CreateWindow(TEXT("button"), TEXT("button1"),              
             WS_VISIBLE | WS_CHILD | BS_BITMAP|BS_FLAT,
             675, 720, 105, 35,  
             hwnd, (HMENU) pgn, NULL, NULL);
    button2=CreateWindow(TEXT("button"), TEXT("button2"),              
           WS_VISIBLE | WS_CHILD | BS_BITMAP|BS_FLAT,
           675, 720, 105, 35,  
           hwnd, (HMENU) pgn, NULL, NULL);

和两个图像加载为:

    HBITMAP img1,img2;
    static HINSTANCE g_hInst=NULL;
    img1 = LoadBitmap(g_hInst,"a100");
    img2 = LoadBitmsp(g_hInst,"a101");

我想按下button1时打印img1,按下button2时打印img2。我使用了以下代码:

    BITMAP bm;

    case WM_CREATE:
    GetObject(img1, sizeof(bm), &bm);

    case WM_COMMAND:

    switch (wParam)
    {
         case pgn:
         PAINTSTRUCT ps;
         HDC hdcWindow;
         hdcWindow = BeginPaint(hwnd, &ps);
         HDC hdcMemory;
         hdcMemory = CreateCompatibleDC(hdcWindow);


         SelectObject(hdcMemory, img1);
         BitBlt(hdcWindow, 150,25,900, bm.bmHeight, hdcMemory, 0, 0,SRCCOPY);

         DeleteDC(hdcMemory);
         EndPaint(hwnd, &ps);     
         break; 

    case pgp:

    hdcWindow = BeginPaint(hwnd, &ps);
    hdcMemory = CreateCompatibleDC(hdcWindow);


    SelectObject(hdcMemory,img2);
    BitBlt(hdcWindow, 150,25,900, bm.bmHeight, hdcMemory, 0, 0,SRCCOPY);

    DeleteDC(hdcMemory);
    EndPaint(hwnd, &ps); 

但它仅适用于第一次按下按钮。我想按下button1时打印img1,按下button2时打印img2。我可以获得更好的代码吗?谁能帮我。 感谢。

1 个答案:

答案 0 :(得分:1)

有一个变量指示应该显示哪个位图。

HBITMAP hbmpSelected = NULL;

按下按钮后,更改变量并调用InvalidateRect。这将导致您的消息循环调度和WM_PAINT处理程序。

// in WM_COMMAND handler
case pgn:
    hbmpSelected = img1;
    InvalidateRect(HWND, NULL);
    break;
case pgp:
    hbmpSelected = img2;
    InvalidateRect(HWND, NULL);
    break;

将所有绘画代码放在WM_PAINT的处理程序中。该代码应该检查变量,以确定在将其打到窗口之前选择哪个位图进入内存DC。

case WM_PAINT:
    PAINTSTRUCT ps;
    HDC hdcWindow = BeginPaint(hwnd, &ps);
    if (hbmpSelected != NULL) {
        HDC hdcMemory = CreateCompatibleDC(hdcWindow);
        HGDIOBJ hbmpOld = SelectObject(hdcMemory, hbmpSelected);
        BitBlt(hdcWindow, 150, 25, 900, bm.bmHeight, hdcMemory, 0, 0, SRCCOPY);
        SelectObject(hdcMemory, hbmpOld);
        DeleteDC(hdcMemory);
    }
    EndPaint(hwnd, &ps);
    break;

(特别是,只在WM_PAINT处理程序中使用BeginPaint和EndPaint。有办法在其他地方绘制到窗口,但这只是在特殊情况下,你不会使用BeginPaint / EndPaint对于那种绘画。)

(还要确保在破坏内存DC之前从内存DC中选择你的位图。现代版本的GDI倾向于容忍这样的错误,但最好直接清理。)

(另请注意,您的按钮是使用相同的ID创建的,pgn。我认为这是一个转录错误,第二个应该是pgp。)