Click here to Skip to main content
12,547,922 members (46,669 online)
Click here to Skip to main content
Add your own
alternative version


39 bookmarked

PostThreadMessage Demystified

, 21 Jun 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
How and Where to use it!


Demystifying the use of much unused and highly advantageous API available for multi-threading!. Code given here is for learning/demo purpose, SHOULDN'T  BE USED DIRECTLY INTO PRODUCTION.  

Using the Code

For years working in multithread environment, I always wonder what's the use of PostThreadMessage? Could it can be utilized in worker thread (though I used the same in UI thread derived from CWinThread).

I am sure every API provided has something for use, otherwise Microsoft programmers are not stupid to provide something which is not working as part of API library. So I created a test program and when playing with worker thread, I provided a message loop inside it with HWND parameter passed as NULL:

// Window MSG Structure
MSG msg;

// Window blocking Message Loop

This means that getmessage can gather message for current thread whether it is thread message or window message. Here is the extract from MSDN.

“If hWnd is NULL, GetMessage retrieves messages for any window that belongs to the current thread, and any messages on the current thread's message queue whose hwnd value is NULL (see the MSG structure). Therefore if hWnd is NULL, both window messages and thread messages are processed.”

Now I added a message handler inside message loop which would wait for say thread message (WM_APP+1) to perform some action, otherwise it with continue with its work. Our fully loaded thread function would look something like this:

DWORD threadProc(LPVOID lParam)
	MSG msg;
		if(msg.message == WM_APP+1)
			MessageBoxA(NULL,"Hello","From Thread",MB_OK);

	MessageBoxA(NULL,"Thread will closed On pressing OK","From Thread",MB_OK);
	return 0;

Now, you are still wondering where our PostThreadMessage API is and how to use it? Now PostThreadMessage API works on thread ID instead of HWND or window handle. Here is a small extract of PostThreadMessage from MSDN:

Posts a message to the message queue of the specified thread. It returns without waiting for the thread to process the message.

BOOL WINAPI PostThreadMessage(
  __in  DWORD idThread,
  __in  UINT Msg,
  __in  WPARAM wParam,
  __in  LPARAM lParam

Now, to get the thread id, when creating thread you have to pass DWORD variable by reference to gather the thread id of newly created worker thread, something like this:

DWORD m_idThread;// in Main Class

Same in _beginthreadex() API, however there is no such arrangement in _beginthread() API to retrieve thread id. Though there are ways, I am not them discussing here, i.e., off topic. Now that you have the thread id of worker thread, using PostThreadMessage you can post message to thread, i.e., for saying hello:


And instructing thread to quit:


Here is how the running application looks like:



Points of Interest

I was more interested in posting it as a tip and tricks; however I thought that posting it as an article would target a larger audience.


  •  21-June-2013 - Updated 
  • 14 July 2011: Posted on CodeProject


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer (Senior)
India India
He used to have biography here Smile | :) , but now he will hire someone (for free offcourse Big Grin | :-D ), Who writes his biography on his behalf Smile | :)

He is Great Fan of Mr. Johan Rosengren (his idol),Lim Bio Liong, Nishant S and DavidCrow and Believes that, he will EXCEL in his life by following there steps!!!

For good 8 years he was Visual CPP MSMVP!

You may also be interested in...

Comments and Discussions

QuestionNot much help Pin
Vaclav_Sal21-Sep-13 4:57
memberVaclav_Sal21-Sep-13 4:57 
AnswerRe: Not much help Pin
ThatsAlok22-Sep-13 21:23
memberThatsAlok22-Sep-13 21:23 
GeneralSimilar technique Pin
Manish K. Agarwal24-Jun-13 0:21
memberManish K. Agarwal24-Jun-13 0:21 
AnswerRe: Similar technique Pin
ThatsAlok26-Jun-13 17:11
memberThatsAlok26-Jun-13 17:11 
GeneralRe: Similar technique Pin
ThatsAlok26-Jun-13 17:15
memberThatsAlok26-Jun-13 17:15 
GeneralRe: Similar technique Pin
Manish K. Agarwal26-Jun-13 21:48
memberManish K. Agarwal26-Jun-13 21:48 
SuggestionCareful there! Pin
Pablo Aliskevicius18-Jul-11 20:36
memberPablo Aliskevicius18-Jul-11 20:36 
GeneralRe: Careful there! Pin
ThatsAlok </18-Jul-11 22:55
member ThatsAlok 18-Jul-11 22:55 
Question[My vote of 1] Breaks the Cardinal Rule of PostThreadMessage Pin
Mike O'Neill18-Jul-11 9:20
memberMike O'Neill18-Jul-11 9:20 
AnswerRe: [My vote of 1] Breaks the Cardinal Rule of PostThreadMessage Pin
ThatsAlok </18-Jul-11 22:47
member ThatsAlok 18-Jul-11 22:47 
Mike O'Neill wrote:
The reason for this rule is explained in the documentation for PostThreadMessage. According to the docs, if there is a user interface for the target thread and the user interface is in a modal loop, such as during resizing and dragging operations, posted messages will be lost.

I never said in this article to use UI in worker thread( being a multi-threaded programmer, I know problems associated with both UI and worker thread)! and MessageBox provided here is for demo purpose only. otherwise i can use trace,outputdebugstring & 'n' number api's present to do my task, however every user/programmer doesn't run demo app in debug mode!.

Mike O'Neill wrote:
, if the recipient thread is in a modal loop (as used by MessageBox or DialogBox), the messages will be lost. To intercept thread messages while in a modal loop, use a thread-specific hook."


The article provdes an example that breaks this cardinal rule by showing a modal dialog.

The article is breaking nothing! what about somebody want to invoke modeless dialog from the thread, here message will not lost, Right !.

Mike O'Neill wrote:
The article provdes an example that breaks this cardinal rule by showing a modal dialog.

that's for demo, who going to use my code directly, here i am just showing how to post message to thread and how to capture it in simple way. i can make it complex by providing WndProc for thread etc, however for keeping it simple I use MessageBox. thats the basic idea behind it.

Mike O'Neill wrote:
Sorry, but IMHO this article does not somehow "demystify" PostThreadMessage, and in fact it actually provides a bad example of its use.

I know that's your personal opinion, however I can just present my viewpoint on it. if it still unclear please let me know!

"Opinions are neither right nor wrong. I cannot change your opinion. I can, however, change what influences your opinion." - David Crow
Never mind - my own stupidity is the source of every "problem" - Mixture

Alok Gupta
VC Forum Q&A :- I/IV
Support CRY- Child Relief and You

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.161021.1 | Last Updated 21 Jun 2013
Article Copyright 2011 by ThatsAlok
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid