Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restore a window without giving it focus using WPF (or interop)

Tags:

c#

wpf

winapi

I need to restore ("un-minimize") a WPF window that has already been created but the window that's currently on top (not necessarily WPF) can't lose focus or activation. I have tried using all WIN32 functions I can find, to no avail. Getting really frustrated by now, would really appreciate any pointers and tips.

Obviously just changing to WindowState.Normal in WPF doesn't cut it as this makes the window receive focus and activation as-well. I have also tried all sorts of combinations with setting Hidden and IsEnabled while restoring.

I have tried WIN32 SetWindowPos with HWND_TOP, HWND_TOPMOST etc. but this function is not intended to restore windows and will only change position of already "displayed" windows.

Tried WIN32 ShowWindow and SetWindowPlacement but no luck there either. Tried a desperate attempt at adding a HwndHook to try and listen for WM_SETFOCUS and restoring focus to the original window but i only get zero for the last focused window handle..

Edit - Solution with window extension after tip from Joel Lucsy:

public static class RestoreWindowNoActivateExtension
{        
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool ShowWindow(IntPtr hWnd, UInt32 nCmdShow);

    private const int SW_SHOWNOACTIVATE = 4;

    public static void RestoreNoActivate(this Window win)
    {
        WindowInteropHelper winHelper = new WindowInteropHelper(win);
        ShowWindow(winHelper.Handle, SW_SHOWNOACTIVATE); 
    }
}
like image 471
Niclas Avatar asked Apr 10 '13 12:04

Niclas


1 Answers

Call ShowWindow passing the SW_SHOWNOACTIVATE flag.

like image 110
Joel Lucsy Avatar answered Nov 04 '22 22:11

Joel Lucsy