tags:

views:

47

answers:

1

I want to prevent activation of all other forms in my winforms application when any dialog is modal. This is how Outlook operates - open two new mail messages, open the address book from one message and you cannot activate the other mail message using either the taskbar or by clicking on the message window. How can I do this in a winforms application (note that setting ownership does not work)?

Sample application below.

using System.Drawing;
using System.Windows.Forms;

namespace ConsoleApplication1
{
   class Program
   {
      static void Main(string[] args)
      {
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new MainForm());
      }
   }

   public class MainForm : Form
   {
      public MainForm()
      {
         Text = "Main Form";
         var button = new Button{Text = "New form"};
         button.Click += (sender, args) => new Form2().Show();
         //button.Click += (sender, args) => { var form = new Form2(); AddOwnedForm(form); form.Show(); };
         Controls.Add(button);
         button.Location = new Point(20, 20);
      }
   }

   public class Form2 : Form
   {
      public Form2()
      {
         Text = "Form 2";
         var button = new Button{Text = "New modal form"};
         button.Click += (sender, args) => new Form{Text = "Modal Dialog", ShowInTaskbar = false}.ShowDialog();
         Controls.Add(button);
         button.Location = new Point(20, 20);
      }
   }
}

To reproduce the behaviour, run the application, open two Form2 instances and then open a modal dialog from the second instance. Then use the taskbar to activate the first Form2 instance and it appears above the modal dialog.

Update: this repros with WPF Windows too.

Update: From Hans' feedback, this does appear to be a bug and I have reported this to connect.microsoft.com here.

A: 

I repro, Win7. I don't see an obvious workaround for it beyond making these forms owned so they don't need a taskbar button. That the Windows window manager allows disabled windows to become active is quite odd. This doesn't get put to test often, very unusual to have one app take so many taskbar buttons.

Hans Passant
Thanks for the repro Hans. Yeah, that would solve the problem, but the app is designed to let the user open up the data forms just like Outlook lets you open emails/appointments/etc.
Sean Kearon
You could try connect.microsoft.com to report the problem. Them taking it serious would require a miracle though.
Hans Passant