#include <windows.h> #include <strsafe.h> LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); void DrawRectangle(HWND hwnd); int cxClient, cyClient; int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { //声明全局数据:类名 static TCHAR szClassName[] = TEXT("MyWindows"); HWND hwnd; MSG msg; //注册窗口类 WNDCLASS wndclass; wndclass.hInstance = hInstance; wndclass.lpszClassName = szClassName; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.lpfnWndProc = WndProc; wndclass.lpszMenuName = NULL; wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION); wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wndclass.style = CS_HREDRAW; if (!RegisterClass(&wndclass)) { MessageBox(NULL, TEXT("this program must run in Windows NT!"), szClassName, MB_ICONERROR); return 0; } hwnd = CreateWindow( szClassName, TEXT("MyFirstPractice"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL ); ShowWindow(hwnd, nShowCmd); UpdateWindow(hwnd); // while (GetMessage(&msg, NULL, 0, 0)) 阻塞函数 这个NULL是指接收当前窗口,包括非客户区的信息,如果设为hwnd则(指的是当前客户区)处理非客户区时,不会响应去退出程序,所以会在后台存在 ??? // { // TranslateMessage(&msg); // DispatchMessage(&msg); // } // #define PM_NOREMOVE 0x0000 // #define PM_REMOVE 0x0001 // #define PM_NOYIELD 0x0002 // #if(WINVER >= 0x0500) // #define PM_QS_INPUT (QS_INPUT << 16) // #define PM_QS_POSTMESSAGE ((QS_POSTMESSAGE | QS_HOTKEY | QS_TIMER) << 16) // #define PM_QS_PAINT (QS_PAINT << 16) // #define PM_QS_SENDMESSAGE (QS_SENDMESSAGE << 16) while (TRUE) { if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))//PM_REMOVE接收后删除 PM_NOREMOVE获取后不删除(偷窥) { if (msg.message==WM_QUIT) { break; } TranslateMessage(&msg); DispatchMessage(&msg); } else { //rand() //0~MAX_RAND 0-32767 //绘制矩形,用到消息处理中的数据(全局) DrawRectangle(hwnd); } } return msg.wParam; } LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { HDC hdc; PAINTSTRUCT ps; RECT rect; // static int cxClient, cyClient; //static是指数据在这个函数中为全局,不是在程序中 switch (message) { case WM_SIZE: cxClient = LOWORD(lParam); cyClient = HIWORD(lParam); break; case WM_PAINT: hdc = BeginPaint(hwnd, &ps); GetClientRect(hwnd, &rect); EndPaint(hwnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(hwnd, message, wParam, lParam); } void DrawRectangle(HWND hwnd) { // TCHAR szBuffer[100]; // StringCchPrintf(szBuffer, 100, L"%d %d", cxClient, cyClient); // MessageBox(NULL, szBuffer, L"Info", NULL); HBRUSH hBrush; HDC hdc; RECT rect; if (cxClient == 0 || cyClient == 0) return; hdc = GetDC(hwnd); SetRect(&rect, rand() % cxClient, rand() % cyClient, rand() % cxClient, rand() % cyClient); hBrush = CreateSolidBrush(RGB(rand() % 256, rand() % 256, rand() % 256)); FillRect(hdc, &rect, hBrush); DeleteObject(hBrush); ReleaseDC(hwnd, hdc); }