Home > Windows API > Posting message to a thread

Posting message to a thread

Use PostThreadMessage API to post message to threads in windows provided you have the thread id of a thread.

Another thing to keep in mind to provide a message loop in your thread proc to watch for messages being posted, which means your thread will be blocked for message processing.

E.g. I assume you have a dialog based application and you have stored id of the thread created somewhere and it’s called m_ThreadId.

BOOL CDialogTestDlg::OnInitDialog()
{
   DWORD WINAPI ThreadProc( LPVOID );
   CreateThread( NULL, NULL, ThreadProc, NULL, 0, &m_ThreadId );

   return FALSE;  // return TRUE  unless you set the focus to a control
}

DWORD MessageID = 13123;
DWORD WINAPI ThreadProc( LPVOID lpv )
{
   UNREFERENCED_PARAMETER( lpv );

   MSG Msg = { 0 };
   while( GetMessage( &Msg, NULL, 0, 0 ))
   {
      switch( Msg.message )
      {
      case MessageID:
         MessageBox( NULL, _T( "Nibu is posting message to a thread" ), _T( "Nibu" ), MB_OK );
      }
   }// End while

   return TRUE;
}

// On button click send message to thread
void CDialogTestDlg::OnButton1()
{
   ASSERT( m_ThreadId ); // Make sure that thread is valid
   PostThreadMessage( m_ThreadId, MessageID, 0, 0 );
}
Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: