Windows程序运行过程

时间:2022-12-24 08:50:23

Windows应用程序:

WinMain函数(入口函数):

1。设计窗口类,注册窗口类;WNDCLASS

2。创建窗口,显示及更新窗口;

3。消息循环;

窗口过程函数(回调函数):WindowProc

PS:Dos程序入口函数为main,Windows程序入口为WinMain,都是由系统直接调用。

windows程序运行过程

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

LRESULT CALLBACK WinSunProc( //窗口过程函数(回调函数)声明
HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam
);

int WINAPI WinMain( //WinMain函数,windows应用程序的入口
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 = WinSunProc;
wndcls.lpszClassName = "hepengtao";
wndcls.lpszMenuName = NULL;
wndcls.style = CS_HREDRAW | CS_VREDRAW;

RegisterClass(&wndcls); //注册窗口类

HWND hwnd;
hwnd = CreateWindow("hepengtao","窗口标题",WS_OVERLAPPEDWINDOW, //创建窗口
0,0,600,400,NULL,NULL,hInstance,NULL);

ShowWindow(hwnd,SW_SHOWNORMAL); //显示窗口
UpdateWindow(hwnd); //更新窗口

MSG msg;
while(GetMessage(&msg,NULL,0,0)) //从消息队列中取出消息,当得到 WM_QUIT 消息时返回0
{
TranslateMessage(&msg);//按下键盘按键时,系统得到 WM_KEYDOWN 和 WM_KEYUP 消息,经过该函数转变为 WM_CHAR 消息
DispatchMessage(&msg); //将得到的消息传递给回调函数
}
return 0;
}

LRESULT CALLBACK WinSunProc(//定义窗口过程函数(回调函数)
HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam
)
{
switch(uMsg)
{
case WM_CHAR: //键盘按下字母后,发送 WM_CHAR 消息
char szChar[20];
sprintf(szChar,"char is %d",wParam);
MessageBox(hwnd,szChar,"弹窗标题",0);
break;
case WM_LBUTTONDOWN: //鼠标左键按下后,发送 WM_LBUTTONDOWN 消息
MessageBox(hwnd,"mouse clicked","弹窗标题",0);
HDC hdc;
hdc = GetDC(hwnd);
TextOut(hdc,0,50,"I am hepengtao.",strlen("I am hepengtao."));
ReleaseDC(hwnd,hdc);
break;
case WM_PAINT: //窗口重绘时,发送 WM_PAINT 消息
HDC hDC;
PAINTSTRUCT ps;
hDC = BeginPaint(hwnd,&ps);
TextOut(hDC,0,0,"Hello,world!",strlen("Hello,world!"));
EndPaint(hwnd,&ps);
break;
case WM_CLOSE: //关闭按钮按下后,发送 WM_CLOSE 消息
if(IDYES == MessageBox(hwnd,"确定要关闭窗口?" ,"弹窗标题",MB_YESNO))
{
DestroyWindow(hwnd); //销毁窗口,并发送 WM_DESTORY 消息
}
break;
case WM_DESTROY: //执行DestoryWindow()函数时,发送 WM_DESTORY 消息
PostQuitMessage(0); //程序请求退出,发送 WM_QUIT 消息
break;
default:
return DefWindowProc(hwnd,uMsg,wParam,lParam); //用户不关心的消息,由操作系统缺省处理
}
return 0;
}