.net 如何在C#中创建一个“不可聚焦”的表单?

yx2lnoni  于 2023-04-22  发布在  .NET
关注(0)|答案(2)|浏览(104)

我希望在C#中创建一个不能接受焦点的窗体,即当我单击窗体上的按钮时,焦点不会从当前具有焦点的应用程序中窃取。
请参阅Windows屏幕键盘的示例。请注意,当您单击按钮时,焦点不会从您当前使用的应用程序中获取。
如何实现此行为?

更新:

原来它是一样简单的覆盖CreateParams属性和添加WS_EX_NOACTIVATE到扩展窗口样式.谢谢你给我指出了正确的方向!
不幸的是,这有一个不受欢迎的副作用,它会扰乱窗体的移动,即您仍然可以在屏幕上拖放窗体,但拖动时窗口的边框不会显示,因此很难精确定位它。
如果有人知道如何解决这个问题,将不胜感激。

lb3vh1jj

lb3vh1jj1#

要禁用鼠标激活,请执行以下操作:

class NonFocusableForm : Form
{
    protected override void DefWndProc(ref Message m)
    {
        const int WM_MOUSEACTIVATE = 0x21;
        const int MA_NOACTIVATE = 0x0003;

        switch(m.Msg)
        {
            case WM_MOUSEACTIVATE:
                m.Result = (IntPtr)MA_NOACTIVATE;
                return;
        }
        base.DefWndProc(ref m);
    }
}

要在不激活的情况下显示表单(在无边界表单的情况下,这是唯一一种对我有效的方法):

[DllImport("user32.dll")]
    public static extern bool ShowWindow(IntPtr handle, int flags);

    NativeMethods.ShowWindow(form.Handle, 8);

标准的方法来做到这一点(似乎它不适用于所有的表单样式):

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

如果有其他激活表单的方法,则可以以类似的方式抑制它们。

nhn9ugyo

nhn9ugyo2#

这是我使用的“NoFocusForm”:

public class NoFocusForm : Form
{
    /// From MSDN <see cref="https://learn.microsoft.com/en-us/windows/win32/winmsg/extended-window-styles"/>
    /// A top-level window created with this style does not become the 
    /// foreground window when the user clicks it. The system does not 
    /// bring this window to the foreground when the user minimizes or 
    /// closes the foreground window. The window should not be activated 
    /// through programmatic access or via keyboard navigation by accessible 
    /// technology, such as Narrator. To activate the window, use the 
    /// SetActiveWindow or SetForegroundWindow function. The window does not 
    /// appear on the taskbar by default. To force the window to appear on 
    /// the taskbar, use the WS_EX_APPWINDOW style.
    private const int WS_EX_NOACTIVATE = 0x08000000;

    public NoFocusForm()
    { 
        // my other initiate stuff
    }

    /// <summary>
    /// Prevent form from getting focus
    /// </summary>
    protected override CreateParams CreateParams
    {
        get
        {
            var createParams = base.CreateParams;

            createParams.ExStyle |= WS_EX_NOACTIVATE;
            return createParams;
        }
    }
}

相关问题