2010-06-06 33 views
2

我在我父母的mdi表格中有一個控件,如果所有的mdi孩子都關閉了,我希望這個控件能夠成爲焦點。我已經嘗試連接到子窗體的FormClosed事件並從那裏設置焦點,但是當我測試它時,我的控件在關閉mdi子項時未留下焦點。如何在所有子窗口關閉時將控件集中在MDIParent中?

有誰能告訴我我錯過了什麼嗎?

在下面的示例中,「第一焦點」被擊中並正確地執行其工作(如果我註釋掉第一個焦點線,我的樹不會專注於啓動,所以它必須在做它的工作,對不對?) 不幸的是,即使「第二焦點」被擊中,當我關閉子窗口時,我的樹並沒有以焦點結束。

重點關注啓動。

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

回答

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())); 
     } 
    } 
+0

奇妙 - 第一次工作 - 謝謝你漢斯! – 2010-06-06 13:33:12

+0

順便說一下,()=> shenanigans是怎麼回事?我在哪裏可以找到關於這個語法的更多信息? – 2010-06-06 13:35:17

+0

這是一個lambda表達式。檢查你最喜歡的C#3.0編程書。 – 2010-06-06 13:50:27

相關問題