代码之家  ›  专栏  ›  技术社区  ›  A. Jacquet

关注一个表单,但不要将其放在其他表单前面

  •  0
  • A. Jacquet  · 技术社区  · 9 年前

    Focus() 方法中,目标表单获得焦点,但也被置于其他表单之前。

    有没有办法避免这种z阶修改?

    下面是一个简短的例子:

    class MyForm : Form
    {
        static void Main(string[] args)
        {
            MyForm f1 = new MyForm()
            {
                Text = "f1"
            };
            f1.Show();
    
            MyForm f2 = new MyForm()
            {
                Text = "f2"
            };
            f2.Show();
    
            Button b1 = new Button();
            b1.Click += (sender, e) => f2.Focus();
            f1.Controls.Add(b1);
    
            Button b2 = new Button();
            b2.Click += (sender, e) => f1.Focus();
            f2.Controls.Add(b2);
    
            Application.Run(f1);
        }
    }
    

    f1 , f2 将获得焦点,但也将出现在前面 f1 (这是我想避免的事情)。

    1 回复  |  直到 9 年前
        1
  •  0
  •   A. Jacquet    9 年前

    我不确定这是最好的方式,但我最终使用了所有者的财产:

    class MyForm : Form
    {
        public const int WM_NCLBUTTONDOWN = 0x00A1;
    
        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case WM_NCLBUTTONDOWN:
                    TakeFocus();
                    base.WndProc(ref m);
                    break;
    
                default:
                    base.WndProc(ref m);
                    break;
            }
        }
    
        private void TakeFocus()
        {
            if (Owner == null && OwnedForms.Length > 0)
            {
                Form tmp = OwnedForms[0];
                tmp.Owner = null;
                Owner = tmp;
            }
            BringToFront();
        }
    
        static void Main(string[] args)
        {
            MyForm f1 = new MyForm()
            {
                Text = "f1",
            };
            f1.Show();
    
            MyForm f2 = new MyForm()
            {
                Text = "f2",
            };
            f2.Owner = f1;
            f2.Show();
    
            Button b1 = new Button();
            b1.Click += (sender, e) =>
            {
                f1.TakeFocus();
            };
            f1.Controls.Add(b1);
    
            Button b2 = new Button();
            b2.Click += (sender, e) =>
            {
                f2.TakeFocus();
            };
            f2.Controls.Add(b2);
    
            Application.Run(f1);
        }
    }
    

    在本例中,当单击一个窗口的客户区时,该窗口在不走到另一个窗口前面的情况下获得焦点。 如果单击非工作区(标题栏和边框)或按钮,表单将获得焦点并显示在前面。