我正在尝试实现一个按钮命令,该命令在用户第一次单击该按钮时启动一个新的 WPF 应用程序,然后(当用户再次单击该按钮时)将其发送到前台(如果它已经在运行)。整个事情正在运行.Net v4.0
当启动的进程是一个普通的 WPF 应用程序时,我尝试做的工作正常,但如果启动的 WPF 应用程序有启动画面,它就不会很好。问题是SetForegroundWindow
失败了,因为在这种特定情况下我无法检索正确的窗口句柄。你能建议一个修复或解决方法吗?假设您可以修改启动器和已启动 WPF 的源。
启动器视图模型中的相关代码
private void ClaimRptLogic()
{
if (ClaimRptHandle != IntPtr.Zero)
{
ShowWindow(ClaimRptHandle, SW_RESTORE);
LaunchState = SetForegroundWindow(ClaimRptHandle)? "" : "can't set to foreground";
return;
}
Process rpt = new Process();
rpt.StartInfo = new ProcessStartInfo()
{
WorkingDirectory = ConfigurationManager.AppSettings["ClaimRptPath"],
FileName = ConfigurationManager.AppSettings["ClaimRptexe"]
};
rpt.Start();
BackgroundWorker bg = new BackgroundWorker();
bg.DoWork += new DoWorkEventHandler((o, e) => {
rpt.WaitForExit();
});
bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler((o, e) => {
ClaimRptHandle = IntPtr.Zero;
LaunchState = "ClaimRpt closed";
});
bg.RunWorkerAsync();
Thread.Sleep(3000);
ClaimRptHandle = rpt.MainWindowHandle;
}