本文介绍了我如何找出是否一个进程正在使用C#已经运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有C#WinForms应用程序需要从时间启动外部EXE时间,但我不希望启动另一个进程,如果一个是已经在运行,而是切换到它。
那么如何在C#中我会因此这在下面的例子?
使用System.Diagnostics程序;...流程富=新的Process();foo.StartInfo.FileName = @C:\\巴\\ foo.exe的;
foo.StartInfo.Arguments =用户名密码;布尔isRunning = // TODO:请检查过程foo.exe的是已经运行
如果(isRunning)
{
// TODO:切换到foo.exe的过程
}
其他
{
foo.Start();
}
解决方案
这应该这样做了你。
//命名空间,我们需要使用
使用System.Diagnostics程序;公共BOOL IsProcessOpen(字符串名称)
{
//这里我们要上获取所有正在运行的进程列表
//计算机
的foreach(在Process.GetProcesses过程clsProcess()){
//现在我们要看看是否有任何正在运行的进程
//匹配当前运行的进程。确保不
// .exe文件添加到您提供的名称,即:记事本,
//没有NOTEPAD.EXE或假总是返回即使
//记事本运行。
//记住,如果你有运行的过程中不止一次,
//说IE打开循环THR路4倍,现在是将关闭所有4,
//如果你希望它只是关闭它找到的第一个
//然后添加一个回报;后杀
如果(clsProcess.ProcessName.Contains(名))
{
//如果过程中发现被随后我们运行
//返回真
返回true;
}
}
//否则返回一个错误
返回false;
}
I have C# winforms application that needs to start an external exe from time to time, but I do not wish to start another process if one is already running, but rather switch to it.
So how in C# would I so this in the example below?
using System.Diagnostics;
...
Process foo = new Process();
foo.StartInfo.FileName = @"C:\bar\foo.exe";
foo.StartInfo.Arguments = "Username Password";
bool isRunning = //TODO: Check to see if process foo.exe is already running
if (isRunning)
{
//TODO: Switch to foo.exe process
}
else
{
foo.Start();
}
解决方案
This should do it for ya.
//Namespaces we need to use
using System.Diagnostics;
public bool IsProcessOpen(string name)
{
//here we're going to get a list of all running processes on
//the computer
foreach (Process clsProcess in Process.GetProcesses()) {
//now we're going to see if any of the running processes
//match the currently running processes. Be sure to not
//add the .exe to the name you provide, i.e: NOTEPAD,
//not NOTEPAD.EXE or false is always returned even if
//notepad is running.
//Remember, if you have the process running more than once,
//say IE open 4 times the loop thr way it is now will close all 4,
//if you want it to just close the first one it finds
//then add a return; after the Kill
if (clsProcess.ProcessName.Contains(name))
{
//if the process is found to be running then we
//return a true
return true;
}
}
//otherwise we return a false
return false;
}
这篇关于我如何找出是否一个进程正在使用C#已经运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!