我有一个表单会弹出在用户的屏幕上,并设置了 TopMost=true
,但它会窃取焦点。如何让它在首次出现时不窃取焦点?
这是我使用的方法。它可以提供最高层级窗口但不会抢占焦点。
protected override bool ShowWithoutActivation
{
get { return true; }
}
private const int WS_EX_TOPMOST = 0x00000008;
protected override CreateParams CreateParams
{
get
{
CreateParams createParams = base.CreateParams;
createParams.ExStyle |= WS_EX_TOPMOST;
return createParams;
}
}
记得在Visual Studio设计器或其他地方省略设置TopMost。
这段内容是从这里(点击Workarounds)偷来的:
将这段代码粘贴到您的表单中:
protected override bool ShowWithoutActivation
{
get { return true; }
}
this.TopMost = True;
在该表单的“加载”事件中。
我没问题!
private const int SW_SHOWNOACTIVATE = 4;
private const int HWND_TOPMOST = -1;
private const uint SWP_NOACTIVATE = 0x0010;
[System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SetWindowPos")]
private static extern bool SetWindowPos(
int hWnd, // Window handle
int hWndInsertAfter, // Placement-order handle
int X, // Horizontal position
int Y, // Vertical position
int cx, // Width
int cy, // Height
uint uFlags); // Window positioning flags
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool ShowWindow(System.IntPtr hWnd, int nCmdShow);
public static void ShowInactiveTopmost(System.Windows.Forms.Form frm)
{
try
{
ShowWindow(frm.Handle, SW_SHOWNOACTIVATE);
SetWindowPos(frm.Handle.ToInt32(), HWND_TOPMOST,
frm.Left, frm.Top, frm.Width, frm.Height,
SWP_NOACTIVATE);
}
catch (System.Exception ex)
{
// error handling
}
}
我使用form1上的计时器测试了下面的代码,以实例化并显示具有form1作为所有者的form2。
在form2的Shown事件中,我将焦点设置为所有者,即当前活动的窗体。
我在form1上有一个文本框,并且能够在此过程中持续写入文本框而不失去焦点。
我的form1计时器代码:
private void timer1_Tick(object sender, EventArgs e)
{
Form2 popup = new Form2();
popup.TopMost = true;
popup.Show(this);
timer1.Enabled = false;
}
我的代码在Form2的Shown事件中:
private void Form2_Shown(object sender, EventArgs e)
{
this.Owner.Focus();
}
BOOL WINAPI SetWindowPos(
__in HWND hWnd,
__in_opt HWND hWndInsertAfter,
__in int X,
__in int Y,
__in int cx,
__in int cy,
__in UINT uFlags
);
不要在_activated
事件中编写.setfocus()
,而是将其编写到窗体的.shown
事件中。