csj*_*nst 25 c# external-process winforms
我有C#winforms应用程序,需要不时启动一个外部exe,但我不希望启动另一个进程,如果一个已经运行,而是切换到它.
那么在C#中我将如何在下面的示例中这样做?
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();
}
Run Code Online (Sandbox Code Playgroud)
Dav*_*veK 32
这应该为你做.
//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;
}
aku*_*aku 22
您也可以使用LINQ,
var processExists = Process.GetProcesses().Any(p => p.ProcessName.Contains("<your process name>"));
Run Code Online (Sandbox Code Playgroud)
我在VB运行时中使用了AppActivate函数来激活现有进程.您必须将Microsoft.VisualBasic dll导入C#项目.
using System;
using System.Diagnostics;
using Microsoft.VisualBasic;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
Process[] proc = Process.GetProcessesByName("notepad");
Interaction.AppActivate(proc[0].MainWindowTitle);
}
}
}
Run Code Online (Sandbox Code Playgroud)