Skip to main content
 首页 » 编程设计

c#之关闭表单未在应用程序 openforms 中显示

2024年02月06日11rubylouvre

我使用下面的代码在屏幕上的所有内容之上弹出一个表单,但它不会窃取焦点。

这工作正常,但我现在需要关闭表单,表单本身不会显示在 Application.OpenForms

我该怎么做?

设置并打开表单

frmClientCall frm = new frmClientCall {StartPosition = FormStartPosition.Manual, Text = "Phone Call"}; 
frm.Location = new System.Drawing.Point( 
    Screen.PrimaryScreen.WorkingArea.Width - frm.Width, 
    Screen.PrimaryScreen.WorkingArea.Height - frm.Height - 202 
); 
frm.lblClient.Text = URI; 
frm.ShowInactiveTopmost(); 

防止焦点在表单上的代码

private const int SW_SHOWNOACTIVATE = 4; 
private const int HWND_TOPMOST = -1; 
private const uint SWP_NOACTIVATE = 0x0010; 
 
[DllImport("user32.dll", EntryPoint = "SetWindowPos")] 
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 
 
[DllImport("user32.dll")] 
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); 
 
public void ShowInactiveTopmost() 
{ 
    ShowWindow(Handle, SW_SHOWNOACTIVATE); 
    SetWindowPos(Handle.ToInt32(), HWND_TOPMOST, Left, Top, Width, Height, SWP_NOACTIVATE); 
 
} 

请您参考如下方法:

是的,这不是唯一的事故。例如,您还可以看到窗体的 Load 事件从未触发。基本问题是您正在绕过正常逻辑,这在 Winforms 中是一个相当大的问题,因为它会延迟创建 native 窗口。在您的情况下,当您使用 Handle 属性时会发生这种情况。我认为潜在的问题是 Visible 属性从未设置为 true,这是真正让球滚动的那个。

好吧,别这样,Winforms 已经支持在不激活窗口的情况下显示窗口。将此代码粘贴到您想要显示的表单中,无需激活:

    protected override bool ShowWithoutActivation { 
        get { return true; } 
    } 

也不需要 SetWindowPos() pinvoke 使其位于最顶部,粘贴此代码:

    protected override CreateParams CreateParams { 
        get { 
            var cp = base.CreateParams; 
            cp.ExStyle |= 8;  // Turn on WS_EX_TOPMOST 
            return cp; 
        } 
    }