tags:

views:

382

answers:

2

In my application I have a window I use for plotting debug data. When it loads, I would like to open it "in the background", behind all other windows.

What's the best way to achieve this?

A: 

Is there any particular reason you don't want to show the window in minimized state and allow user to show it? If showing window in minimized state solves your problem, use

<Window WindowState="Minimized" (...)>
maciejkow
I want the window to be open from the start in the background. Thanks for your suggestion but it does not help me.
Bab Yogoo
+1  A: 

You can use the following code:

[DllImport("user32.dll")]
static extern bool SetWindowPos(
    IntPtr hWnd,
    IntPtr hWndInsertAfter,
    int X,
    int Y,
    int cx,
    int cy,
    uint uFlags);

const UInt32 SWP_NOSIZE = 0x0001;
const UInt32 SWP_NOMOVE = 0x0002;

static readonly IntPtr HWND_BOTTOM = new IntPtr(1);

static void SendWpfWindowBack(Window window)
{
    var hWnd = new WindowInteropHelper(window).Handle;
    SetWindowPos(hWnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
}

Source: http://www.aeroxp.org/board/lofiversion/index.php?t4983.html

huseyint
Wow... I was sure there will be a one-liner to take care of that...
Bab Yogoo
So, did my answer worked for you? Then please mark it as accepted.
huseyint
It won't accept the "DllImport", what should I do?
Bab Yogoo
Add using System.Runtime.InteropServices;
huseyint
The code you reported does not work as-is (see the linked thread). You need to add: "const UInt32 SWP_NOACTIVATE = 0x0010;" and replace "SWP_NOSIZE | SWP_NOMOVE" with "SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE". With this modification it is ok.
Palantir
I know this thread is old, but I need some advice. The above code works, but if I then later set `<window>.Topmost` to `true` then nothing happens. I don't want to `Activate()` the window, which seems required after it was send to the back using the above code.
Peet Brits