gpt4 book ai didi

c# - 当所有子窗口都关闭时,如何将控件集中在 MDIParent 中?

转载 作者:太空宇宙 更新时间:2023-11-03 14:29:31 26 4
gpt4 key购买 nike

我的父 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());
}
}
}

最佳答案

我重现,闻起来像是寻找可聚焦项目的 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()));
}
}

关于c# - 当所有子窗口都关闭时,如何将控件集中在 MDIParent 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2984286/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com