【问题标题】:How to focus a control in an MDIParent when all child windows have closed?当所有子窗口都关闭时,如何在 MDIParent 中聚焦控件?
【发布时间】:2010-06-06 13:16:52
【问题描述】:

我的父 mdi 表单中有一个控件,如果所有 mdi 子级都已关闭,我希望获得焦点。我已经尝试挂钩子窗体的 FormClosed 事件并从那里设置焦点,但是当我测试它时,当我关闭 mdi 子时,我的控件没有留下焦点。

谁能告诉我我错过了什么?

在下面的示例中,“第一个焦点”被击中并正确完成了它的工作(如果我注释掉第一个焦点线,我的树不会在启动时获得焦点,所以它一定在完成它的工作,对吗?) 不幸的是,即使“第二个焦点”被击中,当我关闭子窗口时,我的树也没有得到焦点。

专注于启动。

Has focus http://www.programmingforpeople.com/images/stackoverflow/focus1.PNG

关闭子窗口后不聚焦。

No focus http://www.programmingforpeople.com/images/stackoverflow/focus2.PNG


样本

using System;
using System.Windows.Forms;

namespace mdiFocus
{
   class ParentForm : Form
   {
      public ParentForm()
      {
         IsMdiContainer = true;
         tree = new TreeView();
         tree.Nodes.Add("SomeNode");
         tree.Dock = DockStyle.Left;
         Controls.Add(tree);
      }
      protected override void OnShown(EventArgs e)
      {
         Form child = new Form();
         child.MdiParent = this;
         child.Show();
         child.FormClosed += new FormClosedEventHandler(child_FormClosed);
         tree.Focus(); // first focus works ok
      }
      void child_FormClosed(object sender, FormClosedEventArgs e)
      {
         tree.Focus(); // second focus doesn't seem to work, even though it is hit :(
      }
      TreeView tree;
   }

   static class Program
   {
      [STAThread]
      static void Main()
      {
         Application.Run(new ParentForm());
      }
   }
}

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    我重现,闻起来像寻找可聚焦项目的 WF 逻辑在事件之后运行并弄乱了焦点。此类问题可以通过在使用 Control.BeginInvoke() 处理事件之后运行代码来优雅地解决。这很好用:

        private void toolStripButton1_Click(object sender, EventArgs e) {
            Form child = new Form2();
            child.MdiParent = this;
            child.FormClosed += new FormClosedEventHandler(child_FormClosed);
            child.Show();
        }
    
        void child_FormClosed(object sender, FormClosedEventArgs e) {
            if (this.MdiChildren.Length == 1) {
                this.BeginInvoke(new MethodInvoker(() => treeView1.Focus()));
            }
        }
    

    【讨论】:

    • 顺便说一句,() => 恶作剧是怎么回事?在哪里可以找到有关此语法的更多信息?
    • 这是一个 lambda 表达式。查看您最喜欢的 C# 3.0 编程书籍。
    猜你喜欢
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-23
    • 2018-04-06
    相关资源
    最近更新 更多