您如何检查进程是否正在运行? [英] how do you check if a process is running?

查看:151
本文介绍了您如何检查进程是否正在运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我想编写一个简单的程序来检查某个进程,如果该进程正在运行,则会出现一个消息框.这是到目前为止我得到的,但是没有显示消息框.

Hi, I want to make a simple program that checks for a process and if it is running a messagebox will appear. Here is what I got so far but it doesn''t show the messagebox.

private void Form1_Load(object sender, EventArgs e)
       {
           foreach(Process pro in Process.GetProcesses("notepad")) {

               if( pro.ProcessName.Contains("notepad"))
               {
                   MessageBox.Show("hi");
               }




感谢您提前提供帮助.




Thanks for the help in advance.

推荐答案

看起来有些奇怪.带有字符串参数的GetProcesses在作为参数传递的计算机上搜索进程,请参阅: http://msdn .microsoft.com/en-us/library/x8b2hzk8.aspx [ ^ ].

您可以尝试 Process.GetProcessesByName方法(字符串) [
Looks a bit odd. The GetProcesses with a string parameter searches for processes on the machine passed as the parameter, see: http://msdn.microsoft.com/en-us/library/x8b2hzk8.aspx[^].

You could try Process.GetProcessesByName Method (String)[^] instead.


您可以使用属性System.Diagnostics.Process.HasExited.请注意此调用可能引发的异常,它可以帮助您解决其余情况,例如尚未启动过程等.
http://msdn.microsoft.com/en-us/library/system. diagnostics.process.hasexited.aspx [ ^ ].

在大多数情况下,您不应该检查进程状态,而应该简单地进行阻塞调用以等待进程启动:Process.WaitForExit.不用说,在这种情况下,您应该在单独的线程中使用进程.

请参阅: http://msdn.microsoft.com/en-us/library/system .diagnostics.process.aspx [ ^ ].

—SA
You can use the property System.Diagnostics.Process.HasExited. Pay attention for the exceptions this call can throw — it can help you to cover remaining situations, such as when the process has not been started, etc.:
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.hasexited.aspx[^].

In most cases, you should not check the process status but should simply make a blocking call waiting for the process to start: Process.WaitForExit. Needless to say, in this case you should work with a process in a separate thread.

Please see: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx[^].

—SA


这篇关于您如何检查进程是否正在运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆