Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent taskbar activating non-modal forms when a modal dialog is active

Tags:

winforms

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.

like image 553
Sean Kearon Avatar asked Nov 05 '22 10:11

Sean Kearon


1 Answers

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.

like image 113
Hans Passant Avatar answered Nov 22 '22 06:11

Hans Passant