13

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?

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Bab Yogoo
  • 6,669
  • 6
  • 22
  • 17

2 Answers2

25

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
  • 14,953
  • 15
  • 56
  • 78
  • 1
    Add using System.Runtime.InteropServices; – huseyint Jul 28 '09 at 14:56
  • 4
    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 Jan 11 '10 at 10:56
  • I know this thread is old, but I need some advice. The above code works, but if I then later set `.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 Oct 22 '10 at 14:16
  • hmm nice trick. seems to work... Somewhat. I'm trying to develop a widget style application as well, and where I find this answer lacking is that the application is minimized when the user presses the show desktop button. I'd like to keep it over the desktop in that case as well. – memory of a dream Apr 27 '15 at 13:28
2

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
  • 6,403
  • 1
  • 27
  • 26
  • 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 Jul 25 '09 at 06:47