今天QA部門須要進行Performance測試,由於跑job的時間會很長,下班也跑不完。因此想要作一個job運行完畢自動關機的工具。ide
原理就是檢查進程的名稱,若是檢查不到相應的進程,就說明job已經跑完了,能夠關機了。工具
下圖是我作的自動關機工具,選擇相應的進程名(這裏選擇job的進程名),點擊OK以後窗體會隱藏,在後臺監控進程狀態:測試
程序實例只能運行一個,禁止多個實例同時運行,若是後臺已經存在實例,再點擊打開工具會提示:字體
代碼以下:ui
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Diagnostics; namespace AutoShutDown { public partial class MainForm : Form { public MainForm() { //MessageBox.Show(Process.GetCurrentProcess().ProcessName.ToString()); //Only one instance can run at the same time. Process[] tylan = Process.GetProcessesByName("AutoShutDown"); if (tylan.Count() > 1) { MessageBox.Show("Sorry, the instance of this program has already run on this computer. You can not run it again."); System.Diagnostics.Process.GetCurrentProcess().Kill(); } InitializeComponent(); AddProcesses(); } private void AddProcesses() { var processes = System.Diagnostics.Process.GetProcesses(); foreach (var process in processes) { Processes.Items.Add(process.ProcessName.ToString()); } } private void Processes_SelectedIndexChanged(object sender, EventArgs e) { Processes.Text = Processes.SelectedItem.ToString(); } private void OKButton_Click(object sender, EventArgs e) { //Check if the process has been selected. if (Processes.Text == "") { MessageBox.Show("Please select a process first."); } else { //Check the process's status every 5 miniutes. System.Timers.Timer tmr = new System.Timers.Timer(5000); tmr.Elapsed += new System.Timers.ElapsedEventHandler(CheckProcess); tmr.AutoReset = true; tmr.Enabled = true; this.Hide(); } } private void CheckProcess(object source, System.Timers.ElapsedEventArgs e) { int numOfTheProcesses = 0; var processes = System.Diagnostics.Process.GetProcesses(); foreach (var process in processes) { string TheProcessName = ""; if (Processes.InvokeRequired) { Processes.Invoke(new MethodInvoker(delegate { TheProcessName = Processes.Text; })); } if (process.ProcessName == TheProcessName) { //Find the objective process. //MessageBox.Show(TheProcessName); numOfTheProcesses++; } } if (numOfTheProcesses == 0) { //No such process, shut down the computer. MessageBox.Show("The computer is ready to be shut down."); //Shut down the comp System.Diagnostics.Process myProcess = new System.Diagnostics.Process(); myProcess.StartInfo.FileName = "cmd.exe"; myProcess.StartInfo.UseShellExecute = false; myProcess.StartInfo.RedirectStandardInput = true; myProcess.StartInfo.RedirectStandardOutput = true; myProcess.StartInfo.RedirectStandardError = true; myProcess.StartInfo.CreateNoWindow = true; myProcess.Start(); myProcess.StandardInput.WriteLine("shutdown -s -t 0"); } } } }
其中橘黃色字體部分爲關機代碼,紅色字體部分爲每五秒鐘執行一次ChecProcess方法,每五秒檢查一次進程是否存在,若是不存在了,就關機。this