SetROP2函數:設定前景繪製模式,當前繪製的像素值是當前螢幕像素值的反,這樣可以擦出上一次繪製的結果:
模仿 《windows程式設計》第七章BLOCKOUT程式:
code:
[c-sharp] view plaincopyprint?
- #include <windows.h>
-
- LRESULT CALLBACK wndproc(HWND,UINT,WPARAM,LPARAM);
-
- int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd )
- {
- static TCHAR szAppName[] = TEXT ("BlokOut1") ;
- HWND hwnd ;
- MSG msg ;
- WNDCLASS wndclass ;
-
- wndclass.style = CS_HREDRAW | CS_VREDRAW ;
- wndclass.lpfnWndProc = wndproc ;
- wndclass.cbClsExtra = 0 ;
- wndclass.cbWndExtra = 0 ;
- wndclass.hInstance = hInstance ;
- wndclass.hIcon = LoadIcon (NULL, IDI_APPLICATION) ;
- wndclass.hCursor = LoadCursor (NULL, IDC_ARROW) ;
- wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH) ;
- wndclass.lpszMenuName = NULL ;
- wndclass.lpszClassName = szAppName ;
-
- if (!RegisterClass (&wndclass))
- {
- MessageBox (NULL, TEXT ("Program requires Windows NT!"),
- szAppName, MB_ICONERROR) ;
- return 0 ;
- }
-
- hwnd = CreateWindow (szAppName, TEXT ("Mouse Button Demo"),
- WS_OVERLAPPEDWINDOW,
- CW_USEDEFAULT, CW_USEDEFAULT,
- CW_USEDEFAULT, CW_USEDEFAULT,
- NULL, NULL, hInstance, NULL) ;
-
- ShowWindow (hwnd, SW_SHOWNORMAL) ;
- UpdateWindow (hwnd) ;
-
- while (GetMessage (&msg, NULL, 0, 0))
- {
- TranslateMessage (&msg) ;
- DispatchMessage (&msg) ;
- }
- return msg.wParam ;
- }
-
- void Draw(HWND hwnd,POINT ptbeg,POINT ptend)
- {
- HDC hdc;
- hdc=GetDC(hwnd);
- SetROP2(hdc,R2_NOT);//可以把這行注釋掉,看看結果
- SelectObject(hdc,GetStockObject(NULL_BRUSH));
- Rectangle(hdc,ptbeg.x,ptbeg.y,ptend.x,ptend.y);
- ReleaseDC(hwnd,hdc);
- }
-
- LRESULT CALLBACK wndproc(HWND hwnd,UINT message,WPARAM wparam,LPARAM lparam)
- {
- static POINT ptbeg,ptend,Boxbeg,Boxend;
- static BOOL flag1,flag2;
- HDC hdc;
- PAINTSTRUCT ps;
- switch(message)
- {
- case WM_LBUTTONDOWN:
- ptbeg.x=ptend.x=LOWORD(lparam);
- ptbeg.y=ptend.y=HIWORD(lparam);
-
- Draw(hwnd,ptbeg,ptend);
- flag1=TRUE;
- SetCursor(LoadCursor(NULL,IDC_CROSS));
-
- return 0;
- case WM_MOUSEMOVE:
- if (flag1)
- {
- SetCursor(LoadCursor(NULL,IDC_CROSS));
- Draw(hwnd,ptbeg,ptend);
- ptend.x=LOWORD(lparam);
- ptend.y=HIWORD(lparam);
- Draw(hwnd,ptbeg,ptend);
- }
- return 0;
- case WM_LBUTTONUP:
- if (flag1)
- {
- SetCursor(LoadCursor(NULL,IDC_ARROW));
- Draw(hwnd,ptbeg,ptend);
- Boxbeg=ptbeg;
- Boxend.x=LOWORD(lparam);
- Boxend.y=HIWORD(lparam);
- flag1=FALSE;
- flag2=TRUE;
- InvalidateRect(hwnd,NULL,TRUE);
- }
- return 0;
- case WM_PAINT:
- if (flag2)
- { hdc=BeginPaint(hwnd,&ps);
- SelectObject(hdc,GetStockObject(BLACK_BRUSH));
- //Draw(hwnd,Boxbeg,Boxend);
- Rectangle(hdc,Boxbeg.x,Boxbeg.y,Boxend.x,Boxend.y);
- EndPaint(hwnd,&ps);
- }
- return 0;
- case WM_DESTROY:
- PostQuitMessage(0);
- return 0;
- }
- return DefWindowProc(hwnd,message,wparam,lparam);
}