【问题标题】:How do I prevent the original form from losing focus when I show another form?当我显示另一个表单时,如何防止原始表单失去焦点?
【发布时间】:2011-01-13 18:57:59
【问题描述】:

我遇到了一个问题,即我的主表单在打开新表单时失去焦点。我知道我可以使用mainForm.focus() 将焦点恢复回来,但是如果我希望主窗体在打开新窗口时永远不会放弃焦点,我该如何处理?

【问题讨论】:

标签: c# winforms forms focus


【解决方案1】:

您可以通过覆盖属性ShowWithoutActivation 来完成此操作,以便它以您想要显示的形式返回true,而不会从显示它的表单中窃取焦点,在您的情况下,这将是您的主要表单.

【讨论】:

  • 请注意,您必须为要在不激活的情况下显示的每个表单覆盖此属性,而不是在主表单上。否则,完全正确。 +1
【解决方案2】:

Cody Gray 回答了这个问题,我只是通过直接粘贴代码来扩展它。有编辑权限的人可以把它复制到那里,我只关心删除它;)

pinvoke.net 的 ShowWindow 方法:

    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);

    static void ShowInactiveTopmost(Form frm)
    {
        ShowWindow(frm.Handle, SW_SHOWNOACTIVATE);
        SetWindowPos(frm.Handle.ToInt32(), HWND_TOPMOST,frm.Left, frm.Top, frm.Width, frm.Height,SWP_NOACTIVATE);
        frm.TopMost = false;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 2013-11-26
    相关资源
    最近更新 更多