Using User-Interface Threads

The thread function

OK, you've already done worker threads. You know that you provide a function that is called to execute the thread body, and the thread terminates when this function terminates, the thread ends. But what about a user-interface thread? Where is your function?

The answer is that it is CWinThread::Run is the thread function. This is the message pump. When it exits, your thread terminates.

Using the Thread Function

The key methods you might be interested in are virtual methods of your class. You can create these using ClassWizard:

BOOL PreTranlsateMessage(LPMSG msg) allows you to process messages before letting them be handled by the usual message dispatch. If you process the message at this point and do not want it dispatched, you must return TRUE. If you have processed it and want normal processing to continue for it, or you don't want to process it yourself, you return FALSE.

BOOL OnIdle(LONG count) is called as long as you have "idle tasks" to do and there are no other messages. The first time it is called for idle processing the count is 1, and the count is incremented on each subsequent call. If you return TRUE you will be called again, and again, until you return FALSE. Any time there is a new message to be processed, the counter is reset to 0. If you return FALSE, the message loop blocks until a message comes in. 

BOOL InitInstance() is where you can do any setup for your class. For example, this is where I call CoInitialize(NULL) to initialize the COM subsystem to support the SAPI objects I'm calling. Note that CoInitialize is thread-specific and must be called for each thread that is calling ActiveX objects. If InitInstance fails, you should return FALSE. This will cause the thread to terminate.

void ExitInstance() is where you do any cleanup for your class. It is called after the message pump terminates. This is where I do CoUninitialize() to clean up the COM resources allocated for the thread.

BOOL PostThreadMessage(UINT msg, WPARAM wParam, LPARAM lParam) allows you to post a message to the thread. It returns TRUE if successful and FALSE if error.

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Some people, when confronted with a problem, think "I know, I’ll use regular expressions." Now they have two problems.” - Jamie Zawinski