mur*_*ki5 35 c# process-management
我想知道如果程序正在运行,我可以检查特定位置的程序.例如,c:\ loc1\test.exe和c:\ loc2\test.exe中的test.exe有两个位置.我只想知道c:\ loc1\test.exe是否正在运行,而不是所有的test.exe实例.
bru*_*nde 54
bool isRunning = Process.GetProcessesByName("test")
.FirstOrDefault(p => p.MainModule.FileName.StartsWith(@"c:\loc1")) != default(Process);
Run Code Online (Sandbox Code Playgroud)
小智 7
这是我改进的功能:
private bool ProgramIsRunning(string FullPath)
{
string FilePath = Path.GetDirectoryName(FullPath);
string FileName = Path.GetFileNameWithoutExtension(FullPath).ToLower();
bool isRunning = false;
Process[] pList = Process.GetProcessesByName(FileName);
foreach (Process p in pList) {
if (p.MainModule.FileName.StartsWith(FilePath, StringComparison.InvariantCultureIgnoreCase))
{
isRunning = true;
break;
}
}
return isRunning;
}
Run Code Online (Sandbox Code Playgroud)
并将其用作:
ProgramIsRunning(@"c:\loc1\test.exe");
Run Code Online (Sandbox Code Playgroud)
尝试这个...我用它来确定启动时是否已经运行了另一个进程,其名称与我正在尝试启动的exe相同,然后只需将其中一个放到前台,(并且要聚焦)如果已经正在运行...您可以对其进行修改以获取进程名称并测试该特定名称...这将告诉您是否存在使用某个名称运行的进程,而不是从该进程加载的位置...
如果有一个使用指定名称运行的进程,那么如果该进程有一个公开的可访问方法返回它的加载位置,你可以在正在运行的进程上调用该方法,否则,我不知道..
但出于好奇,你为什么要关心,除非他们不同?如果它们在某种程度上有所不同,则使用该差异(无论它是什么)来检测哪些已加载.但是,如果它们是相同的,那么使用哪个磁盘映像加载它又有什么关系呢?
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")]
private static extern bool IsIconic(IntPtr hWnd);
private const int SW_HIDE = 0;
private const int SW_SHOWNORMAL = 1;
private const int SW_SHOWMINIMIZED = 2;
private const int SW_SHOWMAXIMIZED = 3;
private const int SW_SHOWNOACTIVATE = 4;
private const int SW_RESTORE = 9;
private const int SW_SHOWDEFAULT = 10;
private static bool IsAlreadyRunning()
{
// get all processes by Current Process name
Process[] processes =
Process.GetProcessesByName(
Process.GetCurrentProcess().ProcessName);
// if there is more than one process...
if (processes.Length > 1)
{
// if other process id is OUR process ID...
// then the other process is at index 1
// otherwise other process is at index 0
int n = (processes[0].Id == Process.GetCurrentProcess().Id) ? 1 : 0;
// get the window handle
IntPtr hWnd = processes[n].MainWindowHandle;
// if iconic, we need to restore the window
if (IsIconic(hWnd)) ShowWindowAsync(hWnd, SW_RESTORE);
// Bring it to the foreground
SetForegroundWindow(hWnd);
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
您应该迭代所有现有进程,然后检查其 MainModule 属性以获取您要查找的文件名。像这样的东西
using System.Diagnostics;
using System.IO;
//...
string fileNameToFilter = Path.GetFullPath("c:\\loc1\\test.exe");
foreach (Process p in Process.GetProcesses())
{
string fileName = Path.GetFullPath(p.MainModule.FileName);
//cehck for equality (case insensitive)
if (string.Compare(fileNameToFilter, fileName, true) == 0)
{
//matching...
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
53884 次 |
最近记录: |