I was facing a similar problem in an application I was writing. My main UI was a form running on the main thread. I had a help dialog that I wanted to run as a modeless dialog. This was easy to implement, even to the point of ensuring that I only ever had one instance of the help dialog running. Unfortunately, any modal dialogs I used caused the help dialog to lose focus as well - when it was while some of these modal dialogs were running that having the help dialog there would be most useful.
Using ideas mentioned here, and in other places, I managed to overcome this bug.
I declared a thread inside my main UI.
Thread helpThread;
The following code deals with the event fired to open the help dialog.
private void Help(object sender, EventArgs e)
{
//if help dialog is still open then thread is still running
//if not, we need to recreate the thread and start it again
if (helpThread.ThreadState != ThreadState.Running)
{
helpThread = new Thread(new ThreadStart(startHelpThread));
helpThread.SetApartmentState(ApartmentState.STA);
helpThread.Start();
}
}
void startHelpThread()
{
using (HelpDialog newHelp = new HelpDialog(resources))
{
newHelp.ShowDialog();
}
}
I also needed the initialization of the thread added into my constructor to make sure that I was not referencing a null object the first time this code is run.
public MainWindow()
{
...
helpThread = new Thread(new ThreadStart(startHelpThread));
helpThread.SetApartmentState(ApartmentState.STA);
...
}
This makes sure that the thread has only one instance at any given time. The thread itself runs the dialog, and stops once the dialog is closed. Since it runs on a separate thread, creating a modal dialog from within the main UI does not cause the help dialog to hang. I did need to add
helpDialog.Abort();
to the form closing event of my main UI to make sure that the help dialog closes when the application is terminated.
I now have a modeless help dialog which is not affected by any modal dialogs spawned from within my main UI, which is exactly what I wanted. This is safe since there is no communication needed between the main UI and the help dialog.