Friday, July 22, 2011

An Implementation of inter-thread communication between UI thread and Worker threads with WTL

Introduction
The basic concept of this implementation is explained on my previous post.



Implementation
Class Diagram



Event Object
class WtlEventConnector:public CWindowImpl
{
public:
 static WtlEventConnector& GetInstance()
 {
     static WtlEventConnector instance;
  return instance;
 }

 void Initialize()
 {
  if (m_hWnd)
        {
   return;
        }

  HWND hWnd = Create(GetDesktopWindow(), 0, 0, WS_POPUPWINDOW);
  if (!hWnd)
  {
   throw std::runtime_error("WtlEventHandler Window Creation failed");
  }
 }

 bool FireEvent(int nValue, BaseEventHandler* pHandler)
 {
  if (!m_hWnd)
  {
   return false;
  }
  PostMessage(WM_FIRE, nValue, reinterpret_cast(pHandler));
  return true;
 }

 BEGIN_MSG_MAP ( WtlEventHandler )
 MESSAGE_HANDLER ( WM_FIRE, OnFire )
 END_MSG_MAP()

protected:

 LRESULT OnFire(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL bHandled)
 {
  WtlEventTrigger* pHandler;
  pHandler = reinterpret_cast(lParam);
  pHandler->onMainThread(wParam);
  bHandled = TRUE;
  return 0L;
 }

private:
 WtlEventConnector()
 {
 }

 ~WtlEventConnector()
 {
  if (m_hWnd)
  {
   DestroyWindow();
  }
 }
};


WtlEventTrigger::WtlEventTrigger()
{
 CPortalNetThreadChangerWTL::GetInstance().Initialize();
}

void WtlEventTrigger::fire(int value) // NS

{
 WtlEventConnector::GetInstance().FireEvent(value, handler);
}

No comments:

Post a Comment