[C#.NET][VB.NET] 限制呼叫的應用程式執行的時間
對於在.Net的世界裡 Process類別 提供了我們對應用程式的操作,在上一篇 [C#.NET][VB.NET] Process 類別 / 如何 列舉執行中的程式 已經有稍為提到它的用法。
這篇主要是使用 Process類別 呼叫應用程式,待應用程式載入完成後,等待五秒鐘後關閉應用程式
法一:
Step1.使用Process控制項
Step2.取得要執行的應用程式路徑
Step3.開始執行應用程式
Step4.等待載入
Step5.設定等待時間
Step6.進入關閉程序
private void button1_Click(object sender, EventArgs e)
{
//2.取得要執行的應用程式路徑
this.process1.StartInfo.FileName = Environment.GetEnvironmentVariable("WinDir") + "\\Notepad.exe";
//3.開始執行
this.process1.Start();
//4.等待載入
this.process1.WaitForInputIdle();
//5.等待時間
this.process1.WaitForExit(5000);
//6.進入關閉程序
if (this.process1.HasExited == false)//若程式在等待之前關閉 HasExited會等於true
{
if (this.process1.Responding)//判斷程式是否有回應
this.process1.CloseMainWindow();//關閉視窗
else
this.process1.Kill();//無回應則硬殺它
}
}
法二:使用 Process 類別
private void button2_Click(object sender, EventArgs e)
{
//1.建立Process類別
Process myProcess = new Process();
//2.取得要執行的應用程式路徑
myProcess.StartInfo.FileName = Environment.GetEnvironmentVariable("WinDir") + "\\Notepad.exe";
//3.開始執行
myProcess.Start();
//4.等待載入
myProcess.WaitForInputIdle();
//5.等待時間
myProcess.WaitForExit(5000);
//6.進入關閉程序
if (myProcess.HasExited == false)//若程式在等待之前關閉 HasExited會等於true
{
if (myProcess.Responding)//判斷程式是否有回應
myProcess.CloseMainWindow();//關閉視窗
else
myProcess.Kill();//無回應則硬殺它
}
}
CS_限制應用程式執行時間.rar
若有謬誤,煩請告知,新手發帖請多包涵
Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET