Solving development problems  |  About this blog

Archive for the ‘window focus’ tag

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);
}

Written by Avivo

November 9th, 2009 at 11:48 am