Thursday, September 24, 2009

WPF #2 - How to set focus and bring windows to front

Hi guys,
I was developing a WPF application that should open a window after clicking tray icon and bumped with a problem when focusing, The same method would be called whether the window was open or not, so the easiest way I've found to do that is the following:
[DllImport("User32.dll")]
public static extern Int32 SetForegroundWindow(int hWnd);
private void BringToFront()
{
    if (!IsVisible)
        Visibility = Visibility.Visible;
    SetForegroundWindow((new System.Windows.Interop.WindowInteropHelper(this)).Handle);
}