我正在尝试启动一个应用程序并将其放在前面。但是,应用程序启动正常,然后最终落后于启动应用程序。请注意,在已经运行的最小化应用程序上使用类似的方法可以正常工作(为简洁起见,从该示例中删除了该代码) - 它仅在启动应用程序的新实例时无法工作。有任何想法吗?谢谢
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);
}
}
}
}