I'm trying to launch an application and bring it to the front. However, the application launches ok, then ends up going behind the launching app. Note that using a similar approach on an already-running minimized application works fine (that code removed from this sample for brevity) - it only fails to work when launching a new instance of the app. Any ideas? Thanks
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace Launcher
{
class Program
{
[DllImport("User32.dll", SetLastError = true)]
private static extern int SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern Boolean ShowWindow(IntPtr hWnd, Int32 nCmdShow);
[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
private const int SW_SHOWMAXIMIZED = 3;
private static readonly IntPtr HWND_TOP = new IntPtr(0);
private const UInt32 SWP_NOSIZE = 0x0001;
private const UInt32 SWP_NOMOVE = 0x0002;
private const UInt32 SWP_SHOWWINDOW = 0x0040;
static void Main(string[] args)
{
string wd = @"C:\Program Files (x86)\MyFolder";
string fn = "MyApplication.exe";
if (!System.IO.File.Exists(wd + @"\" + fn)) return;
Process p = new Process();
p.StartInfo.WorkingDirectory = wd;
p.StartInfo.FileName = fn;
p.StartInfo.CreateNoWindow = false;
p.Start(); // app launches OK
Thread.Sleep(5000);
SetForegroundWindow(p.MainWindowHandle); // this has no effect
SetWindowPos(p.MainWindowHandle, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
}
}
}
}