nvfumayx
nvfumayx

Reputation: 43

The confusion about windows GDI. Novice Programmer

I'm a chinese student and here is my first question I've asked in a foreign forum. I have written two programs, one can run normally, but the other one failed.

Here is the normal one:

 case WM_PAINT:
      hdc = BeginPaint (hwnd, &ps) ;

      if(fIsTime)
          ShowTime(hdc, &st);
      else
          ShowDate(hdc, &st);

      EndPaint (hwnd, &ps) ;
      return 0 ;

Here is the failed one:

 case WM_PAINT:
      hdc = BeginPaint (hwnd, &ps) ;
      hdcMem = ::CreateCompatibleDC(hdc);
      hBitmap = ::CreateCompatibleBitmap(hdc, cxClient, cyClient);
      ::SelectObject(hdcMem, hBitmap);

      if(fIsTime)
          ShowTime(hdcMem, &st);
      else
          ShowDate(hdcMem, &st);
      ::BitBlt(hdcMem, 0, 0, cxClient, cyClient, hdc, 0, 0, SRCCOPY);

      ::DeleteObject(hBitmap);
      ::DeleteDC(hdcMem);
      EndPaint (hwnd, &ps) ;
      return 0 ;

The only difference between two codes is the WM_Paint code block, the latter one can not display anything. I am confused about where the error is in the latter code?

Upvotes: 4

Views: 141

Answers (1)

Jonathan Potter
Jonathan Potter

Reputation: 37202

Your biggest problem is you have the source and destination DCs swapped around for the BitBlt call. The first parameter should be the destination, not the source.

Also, when you set a bitmap to a DC, you must remember the old value that is returned to you and restore it when you are finished.

Try the following:

  hdc = BeginPaint (hwnd, &ps) ;
  hdcMem = ::CreateCompatibleDC(hdc);
  hBitmap = ::CreateCompatibleBitmap(hdc, cxClient, cyClient);
  hbmpOld = ::SelectObject(hdcMem, hBitmap);

  if(fIsTime)
      ShowTime(hdcMem, &st);
  else
      ShowDate(hdcMem, &st);
  ::BitBlt(hdc, 0, 0, cxClient, cyClient, hdcMem, 0, 0, SRCCOPY);

  ::SelectObject(hdcMem, hbmpOld);
  ::DeleteObject(hBitmap);
  ::DeleteDC(hdcMem);
  EndPaint (hwnd, &ps) ;
  return 0 ;

Upvotes: 5

Related Questions