views:

390

answers:

3

I have written a sample MFC application in which there are two threads: -Main thread ( UI thread) -Worker thread ( non-UI thread)

I have a specific requirement to create a Modal dialog in Non-UI ( worker thread). When I create the CDialog object and call DoModal on the same, it works. The dialog gets created and acts as Modal to the application. ( Win XP SP2 machine) But this does not work in Windows 2003 server machine. The behavior in 2003 server is that, the Modal Dialog goes behind the application main Window and dialog will be brought to front only when I click on Main Window. It is not acting as Modal dialog to my application.

What could be the problem -- any ideas?

If creating UI controls in non-UI thread is the issue then is there any Win32 API which will allow me to link my worker thread to Main UI thread such that DoModal happens in Main thread. I tried AttachThreadInput but it is not working.

+1  A: 

While i don't know about the specifics of dialog handling on Server 2003, the simplest workaround to get on the main thread would be to use a custom window message, do ::SendMessage() and display the dialog in the message handler.

Georg Fritzsche
A: 

I recommend you not to do what the question subject suggests, and confine all UI to one thread. If you need the other thread to communicate with the user, create some messaging mechanism that will ask the UI thread to do it, and transport the results back.

Pavel Radzivilovsky
A: 

First of all, I'd like to agree with other posters that it's probably better to show the dialog on the main UI thread.

However, if you must, you can make a dialog on another thread modal with the following steps:

  1. Pass your active window as an owner when creating the dialog.
  2. When dialog is showing, iterate over your other windows and do them EnableWindow(FALSE). When the dialog is hiding, do the reverse. You will probably have to remember windows' enabled state and restore the original state, not just EnableWindow(TRUE).
  3. Ensure that accelerators and other global commands will be ignored while the dialog is shown.

Note that (2) shouldn't be necessary provided that you do (1), but you've mentioned MFC, and I don't remember exactly how it behaves. It has it's own modal dialog implementation which may not exactly match Win32. If you're lucky, (1) and (3) will be enough.

atzz