《windows程序设计》- 图形基础 - RandRect.c
在这个程序当中我们最重要的是了解了PeekMessage这个函数, 同时理解它与GetMessage的区别:
peek即为”偷看“的意思, 看一下它的定义:
BOOL PeekMessage(
LPMSG lpMsg,
HWND hWnd,
UINT wMsgFilterMin,
UINT wMsgFilterMax,
UINT wRemoveMsg
);
当消息队列中存在消息时, PeekMessage就返回TRUE, 最后一个参数可以为:
PM_REMOVE
PM_NOREMOVE
表示是否在接收到消息的时候从消息队列中删除它们。
与GetMessage的不同:
PeekMessage只要有消息的时候, 这相依返回TRUE, 即使消息是WM_QUIT, 没有消息的时候, 它不会等待,
而是立即返回,并返回FALSE。而GetMessage则是从消息队列中取出消息并删除它们, 当消息队列是空的时候,它会一直等待,直到队列中存在消息, 当收到WM_QUIT消息时, 它返回FALSE, 这是GetMessage惟一返回FALSE的情况, 其它都会返回TRUE, 代表一直等待或处理消息。
请记住:不管是PeekMessage还是GetMessage, 它们都不会删除WM_PAINT消息, 绝不会!!!从队列中删除WM_PAINT消息的情况是当显示区域重新变得有效的时候, 用ValidateRect和ValidateRgn或者BeginPaint和EndPaint来完成, 记住!!!!
哈哈, 不妨运行下面的程序, 你就会明白了:
#include <windows.h>
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
PSTR szCmdLine,
int iCmdShow) {
static TCHAR szAppName[] = TEXT("rect demo");
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 = GetStockObject(WHITE_BRUSH);
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = szAppName;
if(!RegisterClass(&wndclass)) {
MessageBox(NULL, TEXT("Register failure..."),
szAppName, MB_ICONERROR);
return 0;
style="color: rgb(0, 0, 204);">}
hwnd = CreateWindow(szAppName,
szAppName,
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
NULL,
NULL,
hInstance,
NULL);
ShowWindow(hwnd, iCmdShow);
UpdateWindow(hwnd);
while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
if(msg.message == WM_QUIT)
break;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd,
UINT message,
WPARAM wParam,
LPARAM lParam) {
static int cxClient, cyClient;
HDC hdc;
PAINTSTRUCT ps;
TCHAR buffer[5];
static int i;
RECT rect;
switch(message) {
case WM_SIZE:
cxClient = LOWORD(lParam);
cyClient = HIWORD(lParam);
i = 0;
return 0;
case WM_PAINT:
hdc = GetDC(hwnd);
GetClientRect(hwnd, &rect);
DrawText(hdc, buffer, wsprintf(buffer, "%5d",i++ ), &rect,
DT_SINGLELINE | DT_CENTER | DT_VCENTER);
ReleaseDC(hwnd, hdc);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, message, wParam, lParam);
}
文章出处:飞诺网(http://www.diybl.com/course/3_program/c++/cppsl/20100111/188760_3.html)