[英]Focus a form without bringing it in front of the others
當使用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
(這是我想避免的東西)。
不太確定這是最好的方法,但是我最終使用owner屬性:
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);
}
}
在此示例中,當單擊窗口的工作區時,窗口將獲得焦點而不移到另一個窗口的前面。 如果單擊非工作區(標題欄和邊框)或按鈕,則表單將獲得焦點並位於前面。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.