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;
w.ResizeMode=NoResize;
w.Show();

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:

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

public class Interop
{
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

[DllImport("user32.dll")]
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)
{
Interop.SetForegroundWindow(window);
}
  • 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 taskbar..how to avoid?

  • Dave

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