Disable WPF Window Focus

前端 未结 5 1957
青春惊慌失措
青春惊慌失措 2020-12-06 00:10

I have a WPF Window that shows up only when you hold down the tab key via Visibility.Hidden and Visibility.Visible. However, holding the key down shifts the focus from the a

5条回答
  •  遥遥无期
    2020-12-06 00:42

    You can prevent a WPF Window from activating on mouse click by adding a custom WndProc and handling WM_MOUSEACTIVATE:

    protected override void OnSourceInitialized(EventArgs e)
    {
        base.OnSourceInitialized(e);
        var source = PresentationSource.FromVisual(this) as HwndSource;
        source.AddHook(WndProc);
    }
    private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        if (msg == WM_MOUSEACTIVATE)
        {
            handled = true;
            return new IntPtr(MA_NOACTIVATE);
        }
        else return IntPtr.Zero;
    }
    private const int WM_MOUSEACTIVATE = 0x0021;
    private const int MA_NOACTIVATE = 0x0003;
    

    References:

    • MSDN WM_MOUSEACTIVATE: https://msdn.microsoft.com/en-us/library/windows/desktop/ms645612(v=vs.85).aspx
    • How to handle WndProc messages in WPF: How to handle WndProc messages in WPF?
    • Notification Window – Preventing the window from ever getting focus: Notification Window - Preventing the window from ever getting focus

提交回复
热议问题