MessagePumpThread.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include "StdAfx.h"
  2. #include "MessagePumpThread.h"
  3. CMessagePumpThread::CMessagePumpThread(void)
  4. {
  5. }
  6. CMessagePumpThread::~CMessagePumpThread(void)
  7. {
  8. }
  9. UINT CMessagePumpThread::MessagePumpThread(void* thisptr)
  10. {
  11. CMessagePumpThread *threadClass = (CMessagePumpThread*)thisptr;
  12. threadClass->RunMessagePump();
  13. return 0;
  14. }
  15. void CMessagePumpThread::Start()
  16. {
  17. m_hEvt = CreateEvent(NULL, FALSE, FALSE, NULL);
  18. m_thread = _beginthreadex(NULL, 0, MessagePumpThread, this, 0, &m_threadID);
  19. if (0 == m_thread)
  20. {
  21. throw "Could not create thread";
  22. }
  23. // now wait until the thread is up and really running
  24. if (WAIT_OBJECT_0 != WaitForSingleObject(m_hEvt, 10000L)) // 10 seconds
  25. {
  26. throw "Timeout waiting for thread to start";
  27. }
  28. }
  29. void CMessagePumpThread::Stop()
  30. {
  31. PostThreadMessage(m_threadID, WM_QUIT, 0, 0L);
  32. if (WAIT_OBJECT_0 != WaitForSingleObject(m_hEvt, 10000L))
  33. {
  34. throw "Timeout waiting for thread to stop";
  35. }
  36. };
  37. void CMessagePumpThread::PostMsg(UINT msg, WPARAM wParam, LPARAM lParam)
  38. {
  39. PostThreadMessage(m_threadID, msg, wParam, lParam);
  40. }
  41. void CMessagePumpThread::RunMessagePump()
  42. {
  43. MSG msg;
  44. // create the message queue
  45. PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE);
  46. // we're far enough to let the creator know we're running
  47. SetEvent(m_hEvt);
  48. while(true)
  49. {
  50. BOOL bRet = GetMessage(&msg, NULL, 0, 0);
  51. if (0 >= bRet) // just read the specs, it's a "MickeySoft BOOL" and can be TRUE, FALSE or -1 (right on)
  52. {
  53. SetEvent(m_hEvt);
  54. break;
  55. }
  56. TakeMsg(msg.message, msg.wParam, msg.lParam);
  57. }
  58. }