問題描述:windows
簡單地使用隨即的尺寸和顏色不停的繪製一系列的圖像。dom
一種古老的方式:函數
設置一個向窗口函數發送WM_TIMER消息的windows計時器。ui
對每一個WM_TIMER消息,調用GetDC函數獲取設備環境,而後繪製一個隨機矩形,接着調用ReleaseDC函數釋放設備環境。this
方法弊端:spa
程序不能很快的繪製隨機矩形,必須等待每一個WM_TIMER消息,會依賴於系統時鐘的精度code
新函數:blog
PeekMessage(&msg,NULL,0,0,PM_REMOVE);這個函數容許一個程序檢查程序隊列中的下一個消息,而不是真實的獲取並刪除它看到的消息。隊列
正常的循環消息:it
while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } }
替換後的循環消息:
while(TRUE) { if(PeekMessage(&msg,NULL,0,0,PM_REMOVE)) { if(msg.message == WM_QUIT) break; TranslateMessage(&msg); DispatchMessage(&msg); } else DrawRctangle(hWnd); }
在這裏,必須明確檢查WM_QUIT消息。在一個正常的消息循環中,不須要這樣作。
由於正常的GetMessage返回值是false(0),可是PeekMessage的返回值是隊列中有沒有消息,所以檢查wm_quit是必要的。
源文件代碼:
// peekmessage.cpp : 定義應用程序的入口點。 // #include "stdafx.h" #include "peekmessage.h" #include <Windows.h> #include <stdlib.h> LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); void DrawRctangle(HWND); int cxClient,cyClient; int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { // TODO: 在此放置代碼。 HWND hWnd; static TCHAR szAppName[] = TEXT("RandRect"); MSG msg; WNDCLASS wcex; wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_PEEKMESSAGE)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = NULL; wcex.lpszClassName = szAppName; if (!RegisterClass(&wcex)) { MessageBox(NULL,TEXT("this program requires Windows ",szAppName,MB_ICONERROR); return 0; } hWnd = CreateWindow(szAppName,TEXT("Random Rectangles"),WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,NULL,NULL,hInstance,NULL); ShowWindow(hWnd,nCmdShow); UpdateWindow(hWnd); while(TRUE) { if(PeekMessage(&msg,NULL,0,0,PM_REMOVE)) { if(msg.message == WM_QUIT) break; TranslateMessage(&msg); DispatchMessage(&msg); } else DrawRctangle(hWnd); } return (int) msg.wParam; } void DrawRctangle(HWND hWnd) { HBRUSH hBrush; HDC hdc; RECT rect; if(cxClient == 0 || cyClient == 0) return; SetRect(&rect,rand()%cxClient,rand()%cyClient,rand()%cxClient,rand()%cyClient); hBrush = CreateSolidBrush( RGB(rand()%256,rand()%256,rand()%256) ); hdc = GetDC(hWnd); FillRect(hdc,&rect,hBrush); ReleaseDC(hWnd,hdc); DeleteObject(hBrush); } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch(message) { case WM_SIZE: cxClient = LOWORD(lParam); cyClient = HIWORD(wParam); return 0; case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(hWnd,message,wParam,lParam); }