您的位置:首页 > 其它

Windows应用程序的消息处理机制

2017-01-04 09:17 435 查看
Windows应用程序的消息处理机制:



1)操作系统接收应用程序窗口信息,将消息传递到应用程序的消息队列中;

2)应用程序在消息循环中,调用GetMessage函数,将消息从队列中一条一条取出来,并进行预处理;

3)应用程序调用DispatchMessage, 将消息传递会给操作系统;

4)操作系统调用窗口过程函数,对消息进行处理(即“系统给应用程序发送了消息”);

实例:

#include <windows.h>
#include <stdio.h>
LRESULT CALLBACK WinSunProc
(
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 = WinSunProc;
wndcls.lpszClassName = "sunxin2006";
wndcls.lpszMenuName = NULL;
wndcls.style = CS_HREDRAW | CS_VREDRAW;
//注册
RegisterClass(&wndcls);
//创建一个窗口
HWND hwnd;
hwnd = CreateWindow("sunxin2006","http://www.sunxin.org",WS_OVERLAPPEDWINDOW,0,0,600,400,NULL,NULL,hInstance,NULL);
//显示及刷新窗口
ShowWindow(hwnd,SW_SHOWNORMAL);
UpdateWindow(hwnd);
//定义消息结构体,开始消息循环
MSG msg;
while(GetMessage(&msg,hwnd,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
//编写窗口过程函数
LRESULT CALLBACK WinSunProc
(
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("程序员之家"));
break;
case WM_PAINT:
HDC hDc;
PAINTSTRUCT ps;
hDc = BeginPaint(hwnd,&ps);
TextOut(hDc,0,0,"http://www.sunxin.org",strlen("http://www.sunxin.org"));
EndPaint(hwnd,&ps);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd,uMsg,wParam,lParam);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  windows 操作系统