在游戏中,触发事件以及发出命令是以消息的形式发出的,所以判断是否有消息产生,就从消息队列中逐个遍历。然而消息队列中不是一直都有消息,当队列中没有消息时,为了防止不继续遍历消息队列,我们用内核对象的同步方式,当有消息插入时激活,消息为空时挂起。下面为封装的消息队列类,以后还会继续完善。
#define MAXMESSAGE 1024
class CXMessageList
{
public:
CXMessageList(void);
~CXMessageList(void){};
public:
MSG* GetTopMessage();
MSG* WaitForMessage();
int GetMessageCount(){return mCount;};
int InsertMessage(MSG *msg);
private:
int mCount;
MSG *mList[MAXMESSAGE];
HANDLE mCS_Message;
};
Cpp:
int CXMessageList::InsertMessage( MSG *msg )
{
if(mCount>MAXMESSAGE)
{
return -1;
}
mList[mCount++] = msg;
SetEvent(mCS_Message);
return 1;
}
MSG* CXMessageList::GetTopMessage()
{
MSG *pMsg = NULL;
//ZeroMemory(pMsg, sizeof(MSG));
if(mCount > 0)
{
pMsg = mList[0];
for(int i = 0; i<mCount-1; i++)
{
mList[i] = mList[i+1];
}
mList[mCount - 1] = NULL;
mCount--;
}
if(mCount == 0)
{
ResetEvent(mCS_Message);
}
return pMsg;
}
MSG * CXMessageList::WaitForMessage()
{
if(mCount>0)
{
return GetTopMessage();
}
else
{
WaitForSingleObject(mCS_Message, INFINITE);
return GetTopMessage();
}
}
CXMessageList::CXMessageList( void )
{
mCount = 0;
ZeroMemory(&mList, MAXMESSAGE*sizeof(MSG*));
char CSName[32];
DWORD ThreadID = GetCurrentThreadId();
sprintf_s(CSName, "MsList - %x", ThreadID);
mCS_Message = CreateEvent(NULL, FALSE, TRUE, CSName);
}