什么是重绘窗口呢?当你的窗口被最小化又被还原时,窗口会收到一条信息:WM_PAINT。这条信息非常重要,因为这时窗口中的子窗口无法正常显示,需要重绘,重绘方式如下:
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd,&ps);
FillRect(hdc,&ps.rcPaint,(HBRUSH)(COLOR_WINDOW+1));
EndPaint(hwnd,&ps);再将它放到 WndProc 函数里:
//在switch(uMsg)里面
case WM_PAINT:
{
PAINTSTRUCT ps;//定义了一个画图用的结构体
HDC hdc = BeginPaint(hwnd,&ps);//定义HDC
FillRect(hdc,&ps.rcPaint,(HBRUSH)(COLOR_WINDOW+1));//重绘窗口
EndPaint(hwnd,&ps);//EndPaint
}现在的源代码:
带注释:
#include<windows.h>
LRESULT CALLBACK WndProc(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam)
{
switch(uMsg)//判断消息
{
case WM_CLOSE://用户关闭了窗口
{
if(MessageBox(hwnd,"Really quit?","Confirm",MB_YESNO)==IDYES)//用户按了"是"
DestroyWindow(hwnd);//销毁窗口
//否则什么都不用做
break;
}
case WM_DESTROY://销毁消息
{
PostQuitMessage(0);//关闭窗口
break;
}
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd,&ps);
FillRect(hdc,&ps.rcPaint,(HBRUSH)(COLOR_WINDOW+1));
EndPaint(hwnd,&ps);
}
}
return DefWindowProc(hwnd,uMsg,wParam,lParam);//其余信息默认处理
}
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)
{
HWND hwnd;
MSG msg;
WNDCLASS wc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hbrBackground = (HBRUSH)(WHITE_BRUSH);//背景
wc.hCursor = LoadCursor(NULL, IDC_ARROW);//光标
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);//图标
wc.hInstance = hInstance;
wc.lpfnWndProc = WndProc;//窗口配置函数
wc.lpszClassName = "MyApplication";//窗口类名
wc.lpszMenuName = NULL;//菜单
wc.style = 0;
RegisterClass(&wc);
hwnd = CreateWindow("MyApplication","Test",WS_OVERLAPPEDWINDOW,0,0,500,500,NULL,NULL,hInstance,NULL);
ShowWindow(hwnd,nCmdShow);
UpdateWindow(hwnd);
while(GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}不带注释
#include<windows.h>
LRESULT CALLBACK WndProc(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam)
{
switch(uMsg)
{
case WM_CLOSE:
{
if(MessageBox(hwnd,"Really quit?","Confirm",MB_YESNO)==IDYES)
DestroyWindow(hwnd);
break;
}
case WM_DESTROY:
{
PostQuitMessage(0);
break;
}
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd,&ps);
FillRect(hdc,&ps.rcPaint,(HBRUSH)(COLOR_WINDOW+1));
EndPaint(hwnd,&ps);
}
}
return DefWindowProc(hwnd,uMsg,wParam,lParam);
}
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)
{
HWND hwnd;
MSG msg;
WNDCLASS wc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hbrBackground = (HBRUSH)(WHITE_BRUSH);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hInstance = hInstance;
wc.lpfnWndProc = WndProc;
wc.lpszClassName = "MyApplication";
wc.lpszMenuName = NULL;
wc.style = 0;
RegisterClass(&wc);
hwnd = CreateWindow("MyApplication","Test",WS_OVERLAPPEDWINDOW,0,0,500,500,NULL,NULL,hInstance,NULL);
ShowWindow(hwnd,nCmdShow);
UpdateWindow(hwnd);
while(GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}