模仿WIN32程序处理消息

时间:2023-03-08 22:20:15
模仿WIN32程序处理消息
#include "stdafx.h"
#include "MyMessage.h"
#include <conio.h>
using namespace std;
#ifdef _DEBUG
#define new DEBUG_NEW
#define DBUG_LOG(st) printf("%s\r\n",st);
#else
#define DBUG_LOG(st)
#endif #define MSG_KEY 0X1224 //有键盘输入
#define MSG_CHAR 0X1225 //有字符输入
#define MSG_QUIT 0X0001 //退出
#define MSG_CLOSE 0X0002 //关闭 //定义消息
struct _MSG
{
int msg; //消息
int param; //消息参数
}; //消息队列
CList<_MSG> _MsgQueue; //消息处理函数
typedef void (*MessageProc)(int msg,int param);
MessageProc _MessageHandler;
void MyMessageProc(int msg,int param); //发送消息---投递消息
void _PostMessage(int msg,int param)
{
_MSG NewMsg;
NewMsg.msg = msg;
NewMsg.param = param; _MsgQueue.AddTail(NewMsg);
} //读取消息队列中的新消息
bool _GetMessage(_MSG* pMsg)
{
while (_MsgQueue.IsEmpty()); _MSG LastMsg = _MsgQueue.RemoveHead();
*pMsg = LastMsg; if (pMsg->msg == MSG_QUIT)
{
return false;
} return true;
} //转换消息
void _TranslateMessage(_MSG *pMsg)
{
//x键为系统键
if (pMsg->msg == MSG_KEY && pMsg->param == _T('x'))
{
pMsg->msg = MSG_CLOSE;
return;
} //将键盘消息转换成字符消息
if (pMsg->msg == MSG_KEY)
{
pMsg->msg = MSG_CHAR;
}
} //分发消息
void _DispatchMessage(_MSG *pMsg)
{
_MessageHandler = MyMessageProc;
//直接调用消息处理函数---MyMessageProc
(*_MessageHandler)(pMsg->msg,pMsg->param);
} //消息大循环,负责读取消息-》分发消息
void MessageLoop(/*MessageProc handler*/)
{
//_MessageHandler = handler; _MSG msg;
while (_GetMessage(&msg))
{
_TranslateMessage(&msg);
_DispatchMessage(&msg);
}
} //对MSG_CHAR的响应
void OnChar(int charInput)
{
DBUG_LOG("进入OnChar函数")
if (charInput == _T('q'))
{
_PostMessage(MSG_QUIT,0);
} cout<<"输入:"<<(char)charInput<<endl;
} //对MSG_CLOSE的响应
void OnClose(int charInput)
{
_PostMessage(MSG_QUIT,0);
} //相似于WIN32编程里的消息处理回调函数
void MyMessageProc(int msg,int param)
{
switch (msg)
{
case MSG_CHAR:
{
OnChar(param);
break;
}
case MSG_CLOSE:
{
OnClose(param);
break;
}
}
} //消息发生器
UINT GatherMessage(LPVOID pParam)
{
while (*(bool*)pParam)
{
//键盘输入
if (_kbhit())
{
int ch = _getch();
_PostMessage(MSG_KEY,ch);
}
}
return 0;
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{ bool flag = true;
//打开消息发生器
AfxBeginThread(GatherMessage,&flag);
//开始消息处理循环
MessageLoop(/*MyMessageProc*/); flag = false;
AfxEndThread(0);
return 0;
}

流程图如下

模仿WIN32程序处理消息