C # 調用外部程式方法

來源:互聯網
上載者:User
this.openFileDialog.ShowDialog();
this.txtFileName.Text = this.openFileDialog.FileName;
ProcessStartInfo info = new ProcessStartInfo();

info.FileName = txtFileName.Text;//外部程式名稱

//設定外部程式工作目錄
info.WorkingDirectory = txtFileName.Text.ToString().Substring(0, this.txtFileName.Text.LastIndexOf("\\"));

this.WorkingDirectory.Text = info.WorkingDirectory;

Process process;
try
{
process = Process.Start(info);//啟動外部程式
}
catch (Win32Exception exception)
{
MessageBox.Show("系統找不到指定的程式檔案:" + exception.Message);
return;
throw;
}
this.startTime.Text = process.StartTime.ToString();//外部程式運行開始時間

process.WaitForExit(3000);//設定等待3秒後由主程式進行關閉外部程式

if (process.HasExited == false)
{
this.exitType.Text = "由主程式強制終止外部程式運行";
process.Kill();//強制關閉外部程式
this.endTime.Text = DateTime.Now.ToString();
}
else
{
this.exitType.Text = "外部程式正常退出";
this.endTime.Text = process.ExitTime.ToString();//外部程式執行結束退出時間
}

監測外部程式是否退出:

 process.EnableRaisingEvents = true;
 process.Exited += new EventHandler(process_Exited);

public void process_Exited(object sender, EventArgs e)
{
MessageBox.Show("已監測到外部程式退出。");
}

另外:

監測外部程式是否退出的兩個方法:以運行系統記事本為例 

方法一:這種方法會阻塞當前進程,直到啟動並執行外部程式退出
System.Diagnostics.Process exep = System.Diagnostics.Process.Start(@"C:\Windows\Notepad.exe");
exep.WaitForExit();//關鍵,等待外部程式退出後才能往下執行
MessageBox.Show("Notepad.exe運行完畢");

方法二:為外部進程添加一個事件監視器,當退出後,擷取通知,這種方法時不會阻塞當前進程,你可以處理其它事情
System.Diagnostics.Process exep = new System.Diagnostics.Process();
exep.StartInfo.FileName = @"C:\Windows\Notepad.exe";
exep.EnableRaisingEvents = true;
exep.Exited += new EventHandler(exep_Exited);
exep.Start();

//exep_Exited事件處理代碼,這裡外部程式退出後啟用,可以執行你要的操作
void exep_Exited(object sender, EventArgs e)
{
MessageBox.Show("Notepad.exe運行完畢");
}

 Demo下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.