2011-01-27 3 views
1

アプリケーション内でプロセスを起動しようとしています。以下のコードは、メインGUIのボタンをクリックするとメモ帳を開始するだけです。ノートパッドが起動されると、ボタンは無効になります。メモ帳アプリケーションが終了したときに通知を受け取るためにも、Process.Exitedに登録しました。通知が受け取られたら、もう一度ボタンを有効にしたいと思います。Process.Exitedイベントの受信時に親プロセスのGUIを更新する - WPF

ただし、button1.IsEnabled = trueを呼び出すとコードがクラッシュしました。それはProcess.ExitがメインのGUIスレッドの一部ではないと思われます。したがって、その中でGUIを更新しようとするとクラッシュしました。また、私がデバッグしているときに、私は外部から何かにメインスレッドにアクセスしようとしているという例外を受け取りません。

子プロセスが終了したときにGUIに通知する方法はありますか?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Data; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Imaging; 
using System.Windows.Navigation; 
using System.Windows.Shapes; 
using System.ComponentModel; 
using System.Diagnostics; 

namespace ProcessWatch 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
     Process pp = null; 
     public MainWindow() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, RoutedEventArgs e) 
     { 
      pp = new Process(); 
      pp.EnableRaisingEvents = true; 
      pp.Exited += new EventHandler(pp_Exited); 
      ProcessStartInfo oStartInfo = new ProcessStartInfo(); 
      oStartInfo.FileName = "Notepad.exe"; 
      oStartInfo.UseShellExecute = false; 
      pp.StartInfo = oStartInfo; 
      pp.Start(); 
      button1.IsEnabled = false; 
     } 

     void pp_Exited(object sender, EventArgs e) 
     { 
      Process p = sender as Process; 
      button1.IsEnabled = true;    
     } 
    } 
} 

答えて

1

次のことを試してみてください。

void pp_Exited(object sender, EventArgs e){ 
    Dispatcher.BeginInvoke(new Action(delegate {  
     button1.IsEnabled = true;  
    }), System.Windows.Threading.DispatcherPriority.ApplicationIdle, null); 
} 
+0

感謝。できます.. –

関連する問題