我的父母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());
}
}
}
答案 0 :(得分: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()));
}
}