检查特定的exe文件是否正在运行

发布于 2024-08-11 06:45:15 字数 132 浏览 3 评论 0原文

我想知道如何检查特定位置的程序是否正在运行。例如,test.exe 有两个位置:c:\loc1\test.exe 和 c:\loc2\test.exe。我只想知道 c:\loc1\test.exe 是否正在运行,而不是 test.exe 的所有实例。

I want to know how i can check a program in a specific location if it is running. For example there are two locations for test.exe in c:\loc1\test.exe and c:\loc2\test.exe. I only wanted to know if c:\loc1\test.exe is running and not all instances of test.exe.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

愿与i 2024-08-18 06:45:15
bool isRunning = Process.GetProcessesByName("test")
                .FirstOrDefault(p => p.MainModule.FileName.StartsWith(@"c:\loc1")) != default(Process);
bool isRunning = Process.GetProcessesByName("test")
                .FirstOrDefault(p => p.MainModule.FileName.StartsWith(@"c:\loc1")) != default(Process);
彩扇题诗 2024-08-18 06:45:15

这是我改进的功能:

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;
}

并将其用作:

ProgramIsRunning(@"c:\loc1\test.exe");

This is my improved function :

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;
}

and use it as :

ProgramIsRunning(@"c:\loc1\test.exe");
清风不识月 2024-08-18 06:45:15

试试这个...我用它来确定启动时是否已经有另一个进程与我尝试启动的 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;
    }

try this... I use it to determine at startup if another process is already running with the same name as the exe I'm trying to start, and then just bring that one to foreground, (and to focus) if it is already running... You could modify it to take a process name and test for that specific name... This will tell you if there is a process running with a certain name, but not where that process was loaded from ...

If there is a process running with the specified name, then if that process had an exposed accessible method that returns where it was loaded from, you could call that method on the running process, otherwise, I don't know..

But just out of curiosity, why do you care, unless they're different? And if they're different in some way, code to use that difference (whatever it is) to detect which is loaded. But if they're the same how can it matter which on-disk image was used to load it?

    [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;
    }
怼怹恏 2024-08-18 06:45:15

此功能可能会有所帮助:

using System.Diagnostics;

public bool IsProcessOpen(string name)
{
    foreach (Process clsProcess in Process.GetProcesses()) {
        if (clsProcess.ProcessName.Contains(name))
        {
            return true;
        }
    }
    return false;
} 

来源:http://www.dreamincode.net/code/snippet1541.htm< /a>

This function may help:

using System.Diagnostics;

public bool IsProcessOpen(string name)
{
    foreach (Process clsProcess in Process.GetProcesses()) {
        if (clsProcess.ProcessName.Contains(name))
        {
            return true;
        }
    }
    return false;
} 

Source: http://www.dreamincode.net/code/snippet1541.htm

煮茶煮酒煮时光 2024-08-18 06:45:15

您应该迭代所有现有进程,然后检查其 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...
   }
}

You should iterate over all existing processes and then check their MainModule property for the file name you are looking for. Something like this

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...
   }
}
血之狂魔 2024-08-18 06:45:15

像这样的东西。 GetMainModuleFileName 有助于从 x86 访问 x64 进程。

[DllImport("kernel32.dll")]
public static extern bool QueryFullProcessImageName(IntPtr hprocess, int dwFlags, StringBuilder lpExeName, out int size);

private bool CheckRunningProcess(string processName, string path) {

    var processes = Process.GetProcessesByName(processName);

    foreach(var process in processes) {

        var name = GetMainModuleFileName(process);
        if(name == null)
            continue;

        if(string.Equals(name, path, StringComparison.InvariantCultureIgnoreCase))
            return true;
    }

    return false;
}

// Get x64 process module name from x86 process
private static string GetMainModuleFileName(Process process, int buffer = 1024) {

    var fileNameBuilder = new StringBuilder(buffer);
    int bufferLength = fileNameBuilder.Capacity + 1;

    return QueryFullProcessImageName(process.Handle, 0, fileNameBuilder, out bufferLength)
        ? fileNameBuilder.ToString()
        : null;
}

Something like this. GetMainModuleFileName helps to access x64 process from x86.

[DllImport("kernel32.dll")]
public static extern bool QueryFullProcessImageName(IntPtr hprocess, int dwFlags, StringBuilder lpExeName, out int size);

private bool CheckRunningProcess(string processName, string path) {

    var processes = Process.GetProcessesByName(processName);

    foreach(var process in processes) {

        var name = GetMainModuleFileName(process);
        if(name == null)
            continue;

        if(string.Equals(name, path, StringComparison.InvariantCultureIgnoreCase))
            return true;
    }

    return false;
}

// Get x64 process module name from x86 process
private static string GetMainModuleFileName(Process process, int buffer = 1024) {

    var fileNameBuilder = new StringBuilder(buffer);
    int bufferLength = fileNameBuilder.Capacity + 1;

    return QueryFullProcessImageName(process.Handle, 0, fileNameBuilder, out bufferLength)
        ? fileNameBuilder.ToString()
        : null;
}
葬花如无物 2024-08-18 06:45:15

您可以使用命名互斥体,其名称为脱离程序运行的目录结构。

You could use a named mutex, that's named off of the directory structure the program is running in.

赠我空喜 2024-08-18 06:45:15
System.Reflection.Assembly.GetEntryAssembly()

这将为您带来有关入口程序集的大量信息,例如:

System.Reflection.Assembly.GetEntryAssembly().CodeBase;

这将告诉正在运行的程序集的位置。

System.Reflection.Assembly.GetEntryAssembly()

This will bring for you a lot of info about the entry assembly, such as:

System.Reflection.Assembly.GetEntryAssembly().CodeBase;

This will tell the location of the running assembly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文