我正在尝试启动一个应用程序,并将其放在最前面。然而,应用程序启动时是ok的,然后最终会落后于启动应用程序。请注意,在已经运行的最小化应用程序上使用类似的方法可以很好地工作(为简洁起见,从该示例中删除的代码)-只有在启动应用程序的新实例时才会失败。有什么想法吗?谢谢
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);
}
}
}
}发布于 2016-01-05 18:30:11
好的,在阅读了这里的更多问题后,我设法解决了这个问题,使用了WaitForInputIdle和一个do循环的组合,该循环检查要设置的窗口标题(这是我在代码中做的),以确保应用程序在调用SetForegroundWindow之前已经稳定下来。希望这能帮助其他人
https://stackoverflow.com/questions/23500086
复制相似问题