事件_消息_消息处理函数
- 消息
消息是对事件的描述
typedef struct tagMSG {
HWND hwnd; //窗口句柄
UINT message; //标明消息类型(应用可以只使用低字,高位字系统使用)
WPARAM wParam; //附加信息
LPARAM lParam; //附加信息
DWORD time; //事件发生的事件
POINT pt; //坐标
} MSG, *PMSG;
- 消息处理流程
事件发生》产生消息》传递到系统消息队列》按消息的信息分开转发到对应的应用程序消息队列》循环提取消息》解析消息》判断是否是自己关心的,是就调用消息处理函数,否就转回给系统处理
- 窗口创建
创建窗口类》注册窗口类》创建窗口》显示窗口》消息循环处理
// WND01.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include<stdlib.h>
LRESULT CALLBACK WindowProc(
HWND hwnd, // handle to window
UINT uMsg, // message identifier
WPARAM wParam, // first message parameter
LPARAM lParam // second message parameter
){
return DefWindowProc(hwnd,uMsg,wParam,lParam); //默认将消息丢给系统处理
}
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
// TODO: Place code here.
TCHAR className[] = "My First Window";
//创建窗口类
/*
typedef struct _WNDCLASS {
UINT style;
WNDPROC lpfnWndProc;
int cbClsExtra;
int cbWndExtra;
HINSTANCE hInstance;
HICON hIcon;
HCURSOR hCursor;
HBRUSH hbrBackground;
LPCTSTR lpszMenuName;
LPCTSTR lpszClassName;
} WNDCLASS, *PWNDCLASS;
*/
WNDCLASS wndclass = {0};
wndclass.hbrBackground = (HBRUSH)COLOR_MENU;
wndclass.lpfnWndProc = WindowProc;
wndclass.lpszClassName = className;
wndclass.hInstance = hInstance;
//注册窗口类
RegisterClass(&wndclass);
//创建窗口
HWND hwnd = CreateWindow(
className,
TEXT("我的第一个窗口"),
WS_OVERLAPPEDWINDOW,
10,
10,
600,
300,
NULL,
NULL,
hInstance,
NULL
);
if( hwnd == NULL )
return 0;
//显示窗口
ShowWindow(hwnd,SW_SHOW);
//消息处理
MSG msg;
while(GetMessage(&msg,NULL,0,0)){
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
程序开发误区:
- 编写完,发现一直不显示窗口,后面才发现,窗口类注册时要完整的WNDClass结构
WNDCLASS wndclass;
//正确: WNDCLASS wndclass = {0};
WNDCLASS wndclass;
WNDCLASS wndclass1 = { 0 };
0127182F 33 C0 xor eax,eax
01271831 89 45 A0 mov dword ptr [wndclass1],eax
01271834 89 45 A4 mov dword ptr [ebp-5Ch],eax
01271837 89 45 A8 mov dword ptr [ebp-58h],eax
0127183A 89 45 AC mov dword ptr [ebp-54h],eax
0127183D 89 45 B0 mov dword ptr [ebp-50h],eax
01271840 89 45 B4 mov dword ptr [ebp-4Ch],eax
01271843 89 45 B8 mov dword ptr [ebp-48h],eax
01271846 89 45 BC mov dword ptr [ebp-44h],eax
01271849 89 45 C0 mov dword ptr [ebp-40h],eax
0127184C 89 45 C4 mov dword ptr [ebp-3Ch],eax
可以看到两种方式的实现是不一样的