2011-02-11 83 views
0

后,我正在被设置为始终是最顶层窗口一个WPF应用程序。我在这个应用程序中添加了一个按钮,它启动了一个外部程序,允许用户校准我们的用户将与之交互的触摸屏显示器。启动一个外部进程并设置值时,它完成

我已经可以把我们的主窗口的最上面的设置关闭,启动我的应用程序,但我需要能够这样外部应用程序退出后设置我们MainWindow.Topmost为true。

它已经建议我开始当过程结束,可以最顶层的复位过程中,当添加事件处理程序。事件处理程序对我来说是新手,所以我不知道如何执行此操作。有人能通过它走过我吗?

这里是我目前最上面的禁用我的主窗口,并启动我的应用程序的代码。到目前为止没有多少...

  Application.Current.MainWindow.Topmost = false; 
      System.Diagnostics.Process.Start(@"C:\path\to\app.exe"); 

非常感谢。

(我会在事件处理程序和代表阅读了这个周末!)

回答

2

创建流程,设置EnableRaisingEvents为true,并处理Exited事件:

Process p = new Process(); 
p.StartInfo.FileName = pathToApp; 
p.EnableRaisingEvents = true; 
p.Exited += OnCalibrationProcessExited; // hooks up your handler to the Process 
p.Start(); 

// Now .NET will call this method when the process exits 
private void OnCalibrationProcessExited(object sender, EventArgs e) 
{ 
    // set Topmost 
} 

从评论螺纹,在工作者线程上引发Exited事件,因此您需要使用Dispatcher.BeginInvoke切换到UI线程以设置Topmost:

private void OnCalibrationProcessExited(object sender, EventArgs e) 
{ 
    Action action =() => { /* set Topmost */ }; 
    Dispatcher.BeginInvoke(DispatcherPriority.Normal, action); 
} 

(这里假定代码在你的Window类中。如果没有,你需要写类似Application.Current.MainWindow.Dispatcher.BeginInvoke(...)代替。)

注意我已经分居创建和启动它配置Process对象。虽然这是更详细的,有必要确保所有的事件处理的东西到位之前的过程开始 - 否则,你把处理到位之前,过程可能退出(!不可能的,但理论上是可能的),你的处理程序永远不会被调用。

+0

似乎更容易等待的过程,因为他希望“模态”的行为反正。 – 2011-02-11 22:33:57

1

可以等待的过程中通过Process.WaitForExit退出:

Application.Current.MainWindow.Topmost = false; 
var process = System.Diagnostics.Process.Start(@"C:\path\to\app.exe"); 
process.WaitForExit(); 
Application.Current.MainWindow.Topmost = true; 

如果你想提供一个超时值,以防止永远等待的过程,这也是可能的。例如,如果你想等待最多2分钟,你可以这样做:

process.WaitForExit(2 * 60000); // 60000ms/minute 
相关问题