当我显示另一个表单时,如何防止原始表单失去焦点?

时间:2011-01-13 10:26:54

标签: c# winforms forms focus

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

2 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:1)

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;
    }
相关问题