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

Close form not showing in application openforms

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

这很好用,但我现在需要关闭表单,表单本身不会显示在 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 中是一个相当大的问题,因为它会懒惰地创建本机 window。在您的情况下,当您使用 Handle 属性 时会发生这种情况。我 认为 潜在的问题是 Visible 属性 从未设置为 true,这是真正让球滚动的那个。

好吧,别这样,Winforms 已经支持显示 window 而无需激活它。将这段代码粘贴到你想要显示的表格中,无需激活:

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

也不需要调用 SetWindowPos() 使其最顶层,粘贴此代码:

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