繁体   English   中英

显示另一张表格时,如何防止原始表格失去焦点?

[英]How do I prevent the original form from losing focus when I show another form?

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

您可以通过覆盖属性ShowWithoutActivation来实现此ShowWithoutActivation ,以使其在要显示的表单中返回true ,而不会从显示它的表单中获取焦点,在这种情况下,表单将是您的主要表单。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM