Windows程序内部运行原理的一个示例
一、原理
http://blog.163.com/zhoumhan_0351/blog/static/3995422720103401415721
二、例程
#include "windows.h"
#include "stdio.h"
LRESULT CALLBACK WinWeProc(
HWND hwnd, // handle to window
UINT uMsg, // message identifier
WPARAM wParam, // first message parameter
LPARAM lParam // second message parameter
);
int WINAPI WinMain(
HINSTANCE hInstance, // handle to current instance
HINSTANCE hPrevInstance, // handle to previous instance
LPSTR lpCmdLine, // command line
int nCmdShow // show state
)
{
WNDCLASS wndcls;
wndcls.cbClsExtra=0;
wndcls.cbWndExtra=0;
wndcls.hbrBackground=(HBRUSH)GetStockObject(BLACK_BRUSH);
wndcls.hCursor=LoadCursor(NULL,IDC_CROSS);
wndcls.hIcon=LoadIcon(NULL,IDI_ASTERISK);
wndcls.hInstance=hInstance;
wndcls.lpfnWndProc=WinWeProc;
wndcls.lpszClassName="WinWe2010";
wndcls.lpszMenuName=NULL;
wndcls.style=CS_HREDRAW | CS_VREDRAW;
RegisterClass(&wndcls);
HWND hwnd;
hwnd=CreateWindow("WinWe2010","I am Here",WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,CW_USEDEFAULT,600,400,NULL,NULL,
hInstance,NULL);
ShowWindow(hwnd,SW_SHOWNORMAL);
UpdateWindow(hwnd);
MSG msg;
while(GetMessage(&msg,NULL,0,0)){
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WinWeProc(
HWND hwnd, // handle to window
UINT uMsg, // message identifier
WPARAM wParam, // first message parameter
LPARAM lParam // second message parameter
)
{
switch(uMsg)
{
case WM_CHAR:
char szChar[20];
sprintf(szChar,"char code is %d",wParam);
MessageBox(hwnd,szChar,"char",0);
break;
case WM_LBUTTONDOWN:
MessageBox(hwnd,"mouse","message",0);
HDC hdc;
hdc=GetDC(hwnd);
TextOut(hdc,0,50,"MY home",strlen("MY home"));
ReleaseDC(hwnd,hdc);
break;
case WM_PAINT:
HDC hDc;
PAINTSTRUCT ps;
hDc=BeginPaint(hwnd,&ps);
TextOut(hDc,0,0,"HELLO",strlen("HELLO"));
EndPaint(hwnd,&ps);
break;
case WM_CLOSE:
if(IDYES==MessageBox(hwnd,"Really?","message",MB_YESNO)){
DestroyWindow(hwnd);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd,uMsg,wParam,lParam);
}
return 0;
}
三、注意点
1、wndcls.hbrBackground=(HBRUSH)GetStockObject(BLACK_BRUSH);
2、char szChar[20];
sprintf(szChar,"char code is %d",wParam);
MessageBox(hwnd,szChar,"char",0);
3、hdc=GetDC(hwnd);
TextOut(hdc,0,50,"MY home",strlen("MY home"));
ReleaseDC(hwnd,hdc);
//记得GetDC后要ReleaseDC,否则可能内存泄露。在Windows平台下,所有的图形操作操作都是选用DC的,可以把DC想成画布,我们不是作画者,而是指挥者,指挥DC画什么图形。实际上,DC是一个包含设备(物理设备,如输出设备,显示器,及设备驱动程序等)信息的结构体。DC也是一种资源。
4、hDc=BeginPaint(hwnd,&ps);
TextOut(hDc,0,0,"HELLO",strlen("HELLO"));
EndPaint(hwnd,&ps);
//BeginPaint后要EndPaint,他们是一对,只能用在WM_PAINT消息响应代码中使用。
5、调用UpdateWindow时,会发送WM_PAINT消息给窗口函数,对窗口函数进行刷新。
6、逻辑表达式中,当是判断相等时,如果有常量,应当把常量放前面,方便调试和纠错,如下所示:
if(IDYES==MessageBox(hwnd,"Really?","message",MB_YESNO))
7、变量的命名约定