Search code examples
c#wpffocus

Disable WPF Window Focus


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 active application to the WPF Window. Can I disable this behavior? Going even further: is it possible to completely prevent the window from getting focus even when a control is clicked, but still registering the click action of the control?


Solution

  • Found the answer elsewhere:

    protected override void OnSourceInitialized(EventArgs e)
    {
        base.OnSourceInitialized(e);
    
        //Set the window style to noactivate.
        var helper = new WindowInteropHelper(this);
        SetWindowLong(helper.Handle, GWL_EXSTYLE,
            GetWindowLong(helper.Handle, GWL_EXSTYLE) | WS_EX_NOACTIVATE);
    }   
    
    private const int GWL_EXSTYLE = -20;
    private const int WS_EX_NOACTIVATE = 0x08000000;
    
    [DllImport("user32.dll")]
    public static extern IntPtr SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
    
    [DllImport("user32.dll")]
    public static extern int GetWindowLong(IntPtr hWnd, int nIndex);