Click to See Complete Forum and Search --> : ::PostThreadMessage not working:(


Vaderman
October 4th, 2005, 10:40 AM
I've performed the following steps to create a thread:

HANDLE wait_a_bit = ::CreateEvent(NULL, TRUE, FALSE, RUNNING_EVENT);

::WaitForSingleObject(wait_a_bit, 10); // synchronise threads

// doing some code here... The Thread is created in DLL, then returns the Thread_ID of the newly created thread.
...
bRetVal = ::CloseHandle(wait_a_bit);

...
//Some more code to handle messages sent from RUNNING_EVENT DLL



all this works fine and dandy enough... but when I try and use ::PostThreadMessage(..), the last error code is ERROR_INVALID_THREAD_ID.

Now when I step through my code and using Spy++, I see at the point where the new thread is created from within the DLL, the Thread ID becomes available and is valid, but ::PostThreadMessage is telling me that it isn't!! :mad:

Has anyone any ideas as to what I may be doing wrong?

Regards

John

wildfrog
October 4th, 2005, 10:59 AM
The reason may be that the newly created thread don't have a message queue (yet... I'm not sure why it isn't created right away). Anyway, you can force a thread to initialize its message queue by calling PeekMessage like this:

PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE)

- petter

Vaderman
October 4th, 2005, 11:10 AM
Thanx for the reply wildfrog.

I am assuming that the DLL I'm working with has a Message queue setup.

Besides, how would I create a Message queue for a thread that I have no control of - I cannot change it nor add to it. All I can do is send and receive messages.

I guess that is what you mean - I have to actually add PeekMessage to the DLL to make it work.

Regards

John

wildfrog
October 4th, 2005, 12:39 PM
Well, if you cannot modify the thread code, then MSDN provides another solution:
Call PostThreadMessage. If it fails, call the Sleep function and call PostThreadMessage again. Repeat until PostThreadMessage succeeds.
MSDN also mentions a couple of other situations resulting ERROR_INVALID_THREAD_ID:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/messagesandmessagequeues/messagesandmessagequeuesreference/messagesandmessagequeuesfunctions/postthreadmessage.asp

- petter