Csharp/C#教程:如何知道外部申请是否已关闭?分享


如何知道外部申请是否已关闭?

如果一个winform关闭了怎么说呢?

bool isRunning = false; foreach (Process clsProcess in Process.GetProcesses()) { if (clsProcess.ProcessName.Contains("Notepad")) { isRunning = true; break; } } 

上面的代码总是检查进程是否存在,但是代码对于我想要它做的很慢。那么有没有办法检查Notepad进程是否实际关闭而不是总是循环以查看它是否存在?

您可以使用Win32_ProcessStopTrace指示进程已终止。

 ManagementEventWatcher watcher; protected override void OnLoad(EventArgs e) { base.OnLoad(e); watcher = new ManagementEventWatcher("Select * From Win32_ProcessStopTrace"); watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived); watcher.Start(); } void watcher_EventArrived(object sender, EventArrivedEventArgs e) { if ((string)e.NewEvent["ProcessName"] == "notepad.exe") MessageBox.Show("Notepad closed"); } protected override void OnFormClosed(FormClosedEventArgs e) { watcher.Stop(); watcher.Dispose(); base.OnFormClosed(e); } 

不要忘记添加对System.Management的引用并using System.Management;添加using System.Management;

注意

这应该可以解决问题。 当进程终止时,它将为您创建一个事件。 无需遍历所有过程。

 public static event EventHandler ProcessDied; public void CheckForProcess() { InitializeComponent(); ProcessDied += new EventHandler(Process_Died); AttachProcessDiedEvent("notepad", ProcessDied); } private void AttachProcessDiedEvent( string processName,EventHandler e ) { Process isSelectedProcess=null; foreach (Process clsProcess in Process.GetProcesses()) { if (clsProcess.ProcessName.Contains(processName)) { isSelectedProcess = clsProcess; break; } } if(isSelectedProcess!=null) { isSelectedProcess.WaitForExit(); } if(e!=null) { e.Invoke(processName, new EventArgs()); } } private void Process_Died(object sender, EventArgs e) { //Do Your work } 

如果有任何问题,请告诉我。

你可以不循环但不知道它是否更快:

 bool isRunning = Process.GetProcessesByName("NotePad").FirstOrDefault() != null; 

要么

 bool isRunning = Process.GetProcessesByName("notepad").Any(); 

我从这里得到这个检查特定的exe文件是否正在运行

上述就是C#学习教程:如何知道外部申请是否已关闭?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1026408.html

(0)
上一篇 2022年1月9日
下一篇 2022年1月9日

精彩推荐