64,648
社区成员
发帖
与我相关
我的任务
分享
//Header File
#define QUIT_MSG_HANDLER WM_USER+0x001
#define MSG_HANDLER_TIMEOUT 3000
bool CreateMsgHandler();
void CloseMsgHandler();
friend unsigned int __stdcall ThreadMsgHandler(void *pMainFrame);
HANDLE m_hMsgHandlerEvent;
HANDLE m_hMsgHandler;
UINT m_uiMsgHandlerID;
//Source File
bool CMainFrame::CreateMsgHandler()
{
m_hMsgHandler = INVALID_HANDLE_VALUE;
m_hMsgHandlerEvent = INVALID_HANDLE_VALUE;
m_uiMsgHandlerID = 0;
m_hMsgHandlerEvent = CreateEvent(NULL, FALSE, FALSE, "Msg Handler Event");
if (m_hMsgHandlerEvent == NULL)
{
::MessageBox(NULL,"Create msg handler event error","Warning",MB_OK);
return false;
}
//Create message handler thread
m_hMsgHandler = (HANDLE) _beginthreadex(NULL,1024,ThreadMsgHandler,
(void *) this, 0,(unsigned int *) &m_uiMsgHandlerID);
if (m_hMsgHandler == NULL)
{
::MessageBox(NULL,"Create msg handler thread error","Warning",MB_OK);
return false;
}
switch (WaitForSingleObject(m_hMsgHandlerEvent, MSG_HANDLER_TIMEOUT))
{
case WAIT_OBJECT_0:
break;
case WAIT_TIMEOUT:
default:
::MessageBox(NULL,"Msg handler event not signaled\n","Warning",MB_OK);
return false;
}
return true;
}
//By Reference http://blog.csdn.net/qingfeng_happy5/article/details/3515283
//I change my close msg hander function...
void CMainFrame::CloseMsgHandler()
{
if (m_hMsgHandler != INVALID_HANDLE_VALUE)
{
PostThreadMessage(m_uiMsgHandlerID,QUIT_MSG_HANDLER,(WPARAM) NULL,(LPARAM) NULL);
DWORD dRet;
MSG msg;
while (1)
{
dRet=::MsgWaitForMultipleObjects(1,&m_hMsgHandler,FALSE,INFINITE,QS_ALLINPUT);
if (dRet == WAIT_OBJECT_0+1)
{
while (PeekMessage(&msg,NULL,0,0,PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
else
{
CloseHandle(m_hMsgHandler);
m_hMsgHandler = INVALID_HANDLE_VALUE;
CloseHandle(m_hMsgHandlerEvent);
m_hMsgHandlerEvent = INVALID_HANDLE_VALUE;
break;
}
}
}
}
unsigned int __stdcall ThreadMsgHandler(void * pMainFrame)
{
CMainFrame *pMainFrm = (CMainFrame*)pMainFrame;
MSG msg;
bool bQuit = false;
PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
SetEvent(pMainFrm->m_hMsgHandlerEvent);
while(!bQuit)
{
GetMessage(&msg, NULL, NULL, NULL);
switch (msg.message)
{
case QUIT_MSG_HANDLER:
{
bQuit = true;
break;
}
}
Sleep(10);
}
return 0;
}