从WinMain函数看Windows程序内部运行机制

#include<windows.h>
#include<stdio.h>   

/*

以下为定义的回调函数,回调函数的机制:

  ①定义一个回调函数。

  ②提供函数实现的一方在初始化的时候,将回调函数的指针注册给调用者。

  ③当特定的事情或条件发生的时候,调用者使用函数指针调用回调函数对事件进行处理。

针对window的处理机制,窗口过程函数,被调用的过程如下:

  ①再设计窗口类的时候,将窗口过程函数的地址赋值给lpfnWndProc成员变量;

  ②调用RegisterClass(&wndclass)注册窗口类,那么系统就有了我们所编写的窗口过程函数的地址。

  ③当应用程序接收到某一窗口的消息是,调用DispatchMessage(&msg)将消息回传给系统。系统则利用先前注册窗口类是得到的函数指针,调用窗口过程函数对消息进行处理。

*/

 

LRESULT CALLBACK WinBenProc(           

HWND hwnd,                
UINT uMsg,
WPARAM wParam,
LPARAM lParam);

 

int WINAPI WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow
)
{
//设计一个窗口类
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_ERROR);
wndcls.hInstance=hInstance;
wndcls.lpfnWndProc=WinBenProc;
wndcls.lpszClassName="bingo2012";
wndcls.lpszMenuName=NULL;
wndcls.style=CS_HREDRAW | CS_VREDRAW;
RegisterClass(&wndcls);

//创建窗口
HWND hwnd;
hwnd=CreateWindow("bingo2012","吾辈何以为战",WS_OVERLAPPEDWINDOW,0,0,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 WinBenProc(
HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam
)
{
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 clicked","message",0);
HDC hdc;
hdc=GetDC(hwnd);
TextOut(hdc,0,50,"斌哥不骗你",strlen("斌哥不骗你"));
//ReleaseDC(hwnd,hdc);
break;
case WM_PAINT:
HDC hDc;
PAINTSTRUCT ps;
hDc=BeginPaint(hwnd ,&ps);
TextOut(hDc,0,0,"http://weibo.com/527712389",strlen("http://weibo.com/527712389"));
EndPaint(hwnd,&ps);
break;
case WM_CLOSE:
if(IDYES==MessageBox(hwnd,"是否真的结束","message",MB_YESNO))
{
DestroyWindow(hwnd);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd,uMsg,wParam,lParam);
}
return 0;
}

posted @ 2012-08-19 23:27  斗榖於菟  阅读(1249)  评论(0编辑  收藏  举报