2016-12-15 25 views
0

當使用Focus()方法時,目標表單獲得焦點,但也會引入其他表單之前。將表格集中在其他表格之前

有沒有辦法避免這種z順序修改?

下面是一個簡單的例子:

class MyForm : Form 
{ 
    static void Main(string[] args) 
    { 
     MyForm f1 = new MyForm() 
     { 
      Text = "f1" 
     }; 
     f1.Show(); 

     MyForm f2 = new MyForm() 
     { 
      Text = "f2" 
     }; 
     f2.Show(); 

     Button b1 = new Button(); 
     b1.Click += (sender, e) => f2.Focus(); 
     f1.Controls.Add(b1); 

     Button b2 = new Button(); 
     b2.Click += (sender, e) => f1.Focus(); 
     f2.Controls.Add(b2); 

     Application.Run(f1); 
    } 
} 

f1點擊按鈕,f2將獲得焦點,但也將進來的f1前(這是我想避免的東西)。

+0

將設置f1.TopMost = true;爲你工作? –

+0

您標記了'BringToFront'。這個和/或'SendToBack'可能可以根據需要訂購表單,但最初的改變很可能無法避免,因爲它通常是需要的。 – TaW

+0

@ TroyMac1ure:在某些情況下(例如,如果單擊「f2」),使用TopMost將不起作用,因爲'f2'應該能夠在'f1'前面獲得。 –

回答

0

不能確定它是做到這一點的最好辦法,但我最終使用的所有者屬性:

class MyForm : Form 
{ 
    public const int WM_NCLBUTTONDOWN = 0x00A1; 

    protected override void WndProc(ref Message m) 
    { 
     switch (m.Msg) 
     { 
      case WM_NCLBUTTONDOWN: 
       TakeFocus(); 
       base.WndProc(ref m); 
       break; 

      default: 
       base.WndProc(ref m); 
       break; 
     } 
    } 

    private void TakeFocus() 
    { 
     if (Owner == null && OwnedForms.Length > 0) 
     { 
      Form tmp = OwnedForms[0]; 
      tmp.Owner = null; 
      Owner = tmp; 
     } 
     BringToFront(); 
    } 

    static void Main(string[] args) 
    { 
     MyForm f1 = new MyForm() 
     { 
      Text = "f1", 
     }; 
     f1.Show(); 

     MyForm f2 = new MyForm() 
     { 
      Text = "f2", 
     }; 
     f2.Owner = f1; 
     f2.Show(); 

     Button b1 = new Button(); 
     b1.Click += (sender, e) => 
     { 
      f1.TakeFocus(); 
     }; 
     f1.Controls.Add(b1); 

     Button b2 = new Button(); 
     b2.Click += (sender, e) => 
     { 
      f2.TakeFocus(); 
     }; 
     f2.Controls.Add(b2); 

     Application.Run(f1); 
    } 
} 

在這個例子中,沒有點擊時要在其他窗口前面的窗口獲取焦點它是客戶區。 如果您單擊非客戶端區域(標題欄和邊框)或表單獲得焦點並將其放在前面。