【问题标题】:Toggle between Mdi Children在 Mdi Children 之间切换
【发布时间】:2019-08-02 00:05:50
【问题描述】:

我有一个 MDI 表单,我在其中创建了两个 MDIChild 表单,cf1 和 cf2。 我有一个按钮,当单击该按钮时,应该在 cf1 和 cf2 之间切换“焦点”(即哪个表单在“顶部”)。 在 MDI 父级的构造函数中,我分配了各自 cf1 和 cf2 的 MDIParent。然后我执行 cf1.Show() 然后 cf2.Show(),因此 cf2 最终“在顶部”或“集中”。 当我第一次按下切换按钮时,cf1 变为焦点,cf2 变为非活动状态。 在此之后更改 z 顺序的任何进一步尝试均不成功。

我试过 Activate、ActivateMdiChild、TopMost 和 BringToFront,都没有成功。

using System;
using System.Windows.Forms;

namespace MDITest
{
    public partial class Form1 : Form
    {
        private readonly ChildForm cf1 = new ChildForm();
        private readonly ChildForm cf2 = new ChildForm();

        public Form1()
        {
            InitializeComponent();
            cf1.MdiParent = this;
            cf2.MdiParent = this;
            cf1.Text = "Window 1";
            cf2.Text = "Window 2";
            cf1.Show();
            cf2.Show();
        }

        private void Child_WMSize(object sender, EventArgs e)
        {
            LblWindow1State.Text = $"Window 1 - {cf1.WindowState.ToString()}";
            LblWindow2State.Text = $"Window 2 = {cf2.WindowState.ToString()}";
        }

        private void BtnFocus_Click(object sender, EventArgs e)
        {
            //if (ActiveMdiChild == cf1) cf2.Activate();
            //if (ActiveMdiChild == cf2) cf1.Activate();

            //if (ActiveMdiChild == cf1) ActivateMdiChild(cf2);
            //if (ActiveMdiChild == cf2) ActivateMdiChild(cf1);

            //if (ActiveMdiChild == cf1) cf2.TopMost = true;
            //if (ActiveMdiChild == cf2) cf1.TopMost = true;

            if (ActiveMdiChild == cf1) cf2.BringToFront();
            if (ActiveMdiChild == cf2) cf1.BringToFront();
        }
    }
}

预期的结果是根据需要在两个表单之间切换焦点。实际结果是我只能从cf2改成cf1,反之不行。

我什至尝试过霰弹枪方法:

    if (ActiveMdiChild == cf1)
    {
        cf2.BringToFront();
        cf2.Activate();
        ActivateMdiChild(cf2);
        cf2.TopMost = true;
        cf1.TopMost = false;
    }
    if (ActiveMdiChild == cf2)
    {
        cf1.BringToFront();
        cf1.Activate();
        ActivateMdiChild(cf1);
        cf1.TopMost = true;
        cf2.TopMost = false;
    }

我的结果没有变化。

【问题讨论】:

    标签: c# .net winforms mdi


    【解决方案1】:

    您可以使用以下代码在任意数量的 Mdi 子窗口之间切换:

    if (MdiChildren.Length == 0)
        return;
    var i = Array.IndexOf(MdiChildren, ActiveMdiChild);
    MdiChildren[(MdiChildren.Length + i + 1) % MdiChildren.Length].Activate();
    

    或者

    this.Controls.OfType<MdiClient>().First()
        .SelectNextControl(ActiveMdiChild, true,true, true, true);
    

    或者

    SendKeys.SendWait("^{TAB}"); // Control + TAB as well as Control + F6
    

    【讨论】:

    • 为什么是的,这确实有效 - 您是否可能碰巧知道为什么这种方法有效而我的方法无效?我的意思是,我通过我的代码进行调试,并看到所有变量都将状态更改为我认为应该的状态。但是一旦我退出该方法,似乎什么都没有发生。
    • 我没有调试问题,但 ActivateMdiChild 没有按预期工作。
    猜你喜欢
    • 2011-01-10
    • 1970-01-01
    • 2010-09-05
    • 2014-11-13
    • 2011-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多