AntiStoopMode
AntiStoopMode

Reputation: 281

How to remove focus from wpf window like in close event?

I want to remove focus from my wpf window and set the focus back to the last "windows window" like it happens when I close a normal wpf window.

My WPF Window works like a layer over a normal "Windows Window". I just dont want to lose focus each time I click something on my "layer WPF Windows".

My workaround idea is that I set the focus back to the last "Windows Window" with my Button_Click Event Method.

Hope you can help me, because I was not able to find anything about this uncommon problem on the internet.

Upvotes: 4

Views: 2055

Answers (2)

skink
skink

Reputation: 5756

You'll need to get your hands dirty with P/Invoke. We'll need these functions from WinAPI:

[DllImport("user32.dll")]
static extern IntPtr GetWindow(IntPtr hWnd, uint wCmd);
const uint GW_HWNDNEXT = 2;

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool IsWindowVisible(IntPtr hWnd);

How to use them:

private void Button_Click(object sender, RoutedEventArgs e)
{
    // Get the WPF window handle
    IntPtr hWnd = new WindowInteropHelper(Application.Current.MainWindow).Handle;

    // Look for next visible window in Z order
    IntPtr hNext = hWnd;
    do
        hNext = GetWindow(hNext, GW_HWNDNEXT);
    while (!IsWindowVisible(hNext));

    // Bring the window to foreground
    SetForegroundWindow(hNext);
}

Upvotes: 2

Eric
Eric

Reputation: 245

What you can do is minimizing the window. This will give focus to the "last windows window".

window.WindowState = System.Windows.WindowState.Minimized;

Upvotes: 1

Related Questions