MFC 随机矩形
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
問題描述:
簡單地使用隨即的尺寸和顏色不停的繪制一系列的圖像。
一種古老的方式:
設(shè)置一個(gè)向窗口函數(shù)發(fā)送WM_TIMER消息的windows計(jì)時(shí)器。
對(duì)每個(gè)WM_TIMER消息,調(diào)用GetDC函數(shù)獲取設(shè)備環(huán)境,然后繪制一個(gè)隨機(jī)矩形,接著調(diào)用ReleaseDC函數(shù)釋放設(shè)備環(huán)境。
方法弊端:
程序不能很快的繪制隨機(jī)矩形,必須等待每個(gè)WM_TIMER消息,會(huì)依賴于系統(tǒng)時(shí)鐘的精度
新函數(shù):
PeekMessage(&msg,NULL,0,0,PM_REMOVE);這個(gè)函數(shù)允許一個(gè)程序檢查程序隊(duì)列中的下一個(gè)消息,而不是真實(shí)的獲取并刪除它看到的消息。
正常的循環(huán)消息:
while (GetMessage(&msg, NULL, 0, 0)){if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)){TranslateMessage(&msg);DispatchMessage(&msg);}}替換后的循環(huán)消息:
while(TRUE){if(PeekMessage(&msg,NULL,0,0,PM_REMOVE)){if(msg.message == WM_QUIT)break;TranslateMessage(&msg);DispatchMessage(&msg);}elseDrawRctangle(hWnd);}在這里,必須明確檢查WM_QUIT消息。在一個(gè)正常的消息循環(huán)中,不需要這樣做。
因?yàn)?strong>正常的GetMessage返回值是false(0),但是PeekMessage的返回值是隊(duì)列中有沒有消息,因此檢查wm_quit是必要的。
源文件代碼:
// peekmessage.cpp : 定義應(yīng)用程序的入口點(diǎn)。 // #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);}elseDrawRctangle(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); }轉(zhuǎn)載于:https://my.oschina.net/u/204616/blog/544985
總結(jié)
- 上一篇: ColorStateList 使用详解
- 下一篇: ios Sqlite数据库增删改查基本操