//---------------------------------------------------------------------------#include<windows.h>//===========================================================================long__stdcallWndProc(HWNDhwnd,UINTmsg,WPARAMWParam,LPARAMLParam){switch(msg){caseWM_CLOSE:PostQuitMessage(0);break;caseWM_LBUTTONDOWN:MessageBoxA(0,"ok","提示",0);PostQuitMessage(0);break;caseWM_PAINT:{HDChdc;hdc=GetDC(hwnd);RECTrect;GetClientRect(hwnd,&rect);rect.left=rect.right/2;rect.top=rect.bottom/2;rect.right=rect.left+50;rect.bottom=rect.top+30;DrawText(hdc,"hello",5,&rect,0);ReleaseDC(NULL,hdc);}default:returnDefWindowProc(hwnd,msg,WParam,LParam);}return0;}WINAPIWinMain(HINSTANCEhInstance,HINSTANCEhPreHinstance,LPSTR,int){g_hIns=hInstance;WNDCLASStheClass={0};char*lpszClassName="myClass";char*lpszTitle="测试窗口";HWNDhwnd;MSGmsg;theClass.style=0;//缺省窗口风格theClass.lpfnWndProc=WndProc;theClass.cbClsExtra=0;//窗口类无扩展theClass.cbWndExtra=0;//窗口实例无扩展theClass.hInstance=hInstance;//窗口的最小化图标为缺省图标,即窗口左上角图标//VC中资源ID为IDI_APPLICATION//在BCB中资源名为MAINICONtheClass.hIcon=LoadIcon(hInstance,"MAINICON");theClass.hCursor=LoadCursor(NULL,IDC_ARROW);//窗口采用箭头光标theClass.hbrBackground=(HBRUSH)(GetStockObject(WHITE_BRUSH));//窗口背景为白色theClass.lpszMenuName=NULL;//窗口无菜单theClass.lpszClassName=lpszClassName;//窗口类名为"窗口"if(!RegisterClass(&theClass))//如果注册失败发出警告{MessageBeep(0);returnFALSE;}hwnd=CreateWindow(lpszClassName,//窗口类名lpszTitle,//窗口标题名WS_OVERLAPPEDWINDOW,//窗口的风格CW_USEDEFAULT,//窗口左上角坐标值为缺省值CW_USEDEFAULT,500,300,//窗口的宽和高NULL,//此窗口无父窗口NULL,//此窗口无子菜单hInstance,//创建此窗口的应用程序的当前句柄NULL//不使用该值);ShowWindow(hwnd,SW_SHOW);UpdateWindow(hwnd);while(true){if(PeekMessage(&msg,NULL,0,0,PM_REMOVE)){if(msg.message==WM_QUIT)break;TranslateMessage(&msg);DispatchMessage(&msg);}//if(GetMessage(&msg,NULL,0,0))//{//TranslateMessage(&msg);//DispatchMessage(&msg);//}//else//break;}returnmsg.wParam;//消息循环结束即程序结束时将信息返回系统}

PeekMessage与GetMessage函数处理不相同,两种方式都可以.PeekMessage是不阻塞的,GetMessage是线程阻塞的,内部处理退出消息,所以不用判断退出消息,关闭时,就跳到break结束循环。要在WM_PAINT消息中绘图,可用如下代码:

PAINTSTRUCTps={0};HDChdc=BeginPaint(hwnd,&ps);//HPENhPen=GetStockObject(WHITE_PEN);HPENhPen=CreatePen(PS_DASHDOTDOT,1,RGB(255,0,0));HGDIOBJoldPen=(HGDIOBJ)SelectObject(hdc,hPen);if(!oldPen){interr=GetLastError();charbuff[20]={0};itoa(err,buff,10);OutputDebugStringA(buff);}//画矩形Rectangle(hdc,20,30,80,120);//画线MoveToEx(hdc,20,10,NULL);LineTo(hdc,200,100);SelectObject(hdc,oldPen);DeleteObject(hPen);EndPaint(hwnd,&ps);