App won't come to the foreground when started

Charles He-MSFT 96 Reputation points Microsoft Employee
2020-03-27T07:41:31.56+00:00

This is a MSDN question asked by Will Pittenger, the source is App won't come to the foreground when started.

I have a WPF application that when I start it from Visual Studio, its main Window goes to the background rather than becoming the foremost window. I tried adding the code below to the Window, but had no effect.

protected override void OnInitialized(System.EventArgs e)
{
base.OnInitialized(e);
Activate();
}

What am I doing wrong?

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,647 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Alex Li-MSFT 1,096 Reputation points
    2020-03-27T07:52:06.003+00:00

    Hi,

    Welcome to our Microsoft Q&A platform!

    You can try the following code:

     public partial class MainWindow : Window
        {
            [DllImport("user32.dll")]
            private static extern int SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);
            static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
            const int SWP_SHOWWINDOW = 0x0040;
            public MainWindow()
            {
                InitializeComponent();
                IntPtr handle = new WindowInteropHelper(this).Handle;
                SetWindowPos(handle, HWND_TOPMOST, 0, 0, 100, 200, SWP_SHOWWINDOW);
            }   
        }
    

    Thanks.

    0 comments No comments

  2. Will Pittenger 281 Reputation points
    2020-03-27T13:59:14.41+00:00

    Only one reply from the original thread was copied. The above solution had no effect.

    0 comments No comments