Solving development problems  |  About this blog

How to focus window in WPF when it gets out of focus

Sometimes you want to have your WPF application in “kiosk” mode (fullscreen) and you can do this with this code:

Window w = new Window();
w.WindowStyle = WindowStyle.None;
w.WindowState = WindowState.Maximized;
w.TopMost = true;

But, some system message (yellow balloon in system tray shows Taskbar in focus or any other Window system task) can get your application out of focus. In order to get it back to focus use this code:

using System.Runtime.InteropServices;
using System.Windows.Interop;

public class Interop
public static extern bool SetForegroundWindow(IntPtr hWnd);

public static extern IntPtr GetForegroundWindow();

public static IntPtr GetWindowHandle(Window window)
return new WindowInteropHelper(window).Handle;

//Somewhere in main window
IntPtr window = Interop.GetWindowHandle(this);
IntPtr focused = Interop.GetForegroundWindow();
if (window != focused)
  • johnny

    Works fine on Windows Vista 64-bit, anyone tried in Windows XP or Windows 7?

  • Jon M

    Thank you so much! This is EXACTLY what I needed.

  • Dave

    this is pretty close however users are still able to interact with the to avoid?

  • Dave

    This seems to work nicely, however how do i stop this behavior? i.e. how can i disable setforegroudnwindow?

  • Russell Scott

    Thanks. Spent half a day trying other “solutions”, and this was the only one that worked for me.