2012-01-04 116 views
2

我正在進行窗體應用程序,它也在不同線程上運行控制檯進程。基本上我需要在應用程序退出後取消阻止按鈕。在我完成事件處理程序之前,完成後的過程剛剛停止,但現在,事件之後應用程序本身被終止。應用程序退出進程退出事件

下面是製作過程中運行代碼:

public void CallConsole()//This Calls the console application 
{ 
    Thread.CurrentThread.IsBackground = true; 
    Process p = new Process(); 
    p.StartInfo.UseShellExecute = false; 
    p.StartInfo.RedirectStandardOutput = true; 
    p.StartInfo.RedirectStandardError = true; 
    p.StartInfo.FileName = filename; 
    if (checkBox1.Checked) 
     p.StartInfo.CreateNoWindow = true; 
    p.EnableRaisingEvents = true; 
    p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived); 
    p.ErrorDataReceived += new DataReceivedEventHandler(p_OutputDataReceived); 
    p.Exited += new EventHandler(p_Exited); 
    p.Disposed += new EventHandler(p_Exited); 
    p.Start(); 
    p.BeginErrorReadLine(); 
    p.BeginOutputReadLine(); 
} 

我試着用Thread.IsBackground性質的工作,但這並沒有改變任何東西

這裏的事件處理程序本身:

void p_Exited(object sender, EventArgs e)//Process on exit or disposed will make button1 avalable 
{ 
    button1.Enabled = true; 
} 

任何想法爲什麼添加後應用

p.EnableRaisingEvents = true; 

現在被殺害,不只是過程?

+0

@HansPassant謝謝! – TheBW 2012-01-04 12:56:05

回答

2

的這裏的問題是,

void p_Exited(object sender, EventArgs e)//Process on exit or disposed will make button1 available 
{ 
    button1.Enabled = true; 
} 

需要調用,並沒有任何形式的錯誤處理。一旦我添加了另一個功能,檢查button1.InvokeRequired,如果它確實調用自己再次通過調用它成功了

1

這裏的問題是Exited事件正在線程池線程上觸發。控件只能在UI線程上修改。

你可以稱之爲BeginInvoke,但它更簡單,只是配置Process對象通過設置調用自身:

p.SynchronizingObject = button1; 

Button實現ISynchronizeInvoke,其中Process對象使用調用它的事件。

+0

我正在尋找這種答案。非常感謝。 – Hari 2017-12-06 12:07:47

+0

@哈瑞不用擔心,你非常歡迎。 – 2017-12-07 09:05:23