如何获得在C#活动过程名称? [英] How to Get Active Process Name in C#?

查看:194
本文介绍了如何获得在C#活动过程名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在C#中得到积极的进程名?

How to get active process name in C#?

我知道我必须使用此code:

I know that I must use this code:

[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();

但我不知道如何使用它。

but I don't know how use it.

推荐答案

作为<一提到href=\"http://stackoverflow.com/questions/277085/how-do-i-getmodulefilename-if-i-only-have-a-window-handle-hwnd/321343#321343\">this回答,你必须使用 GetWindowThreadProcessId()来得到该窗口的进程ID,然后你可以使用过程

As mentioned in this answer, you have to use GetWindowThreadProcessId() to get the process id for the window and then you can use the Process:

[DllImport("user32.dll")]
public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, out uint ProcessId);

[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();

string GetActiveProcessFileName()
{
    IntPtr hwnd = GetForegroundWindow();
    uint pid;
    GetWindowThreadProcessId(hwnd, out pid);
    Process p = Process.GetProcessById((int)pid);
    p.MainModule.FileName.Dump();
}

请注意,这似乎抛出异常(A 32位进程无法访问64位进程的模块)时,活动进程是64位,从32位应用程序运行时。

Be aware that this seems to throw an exception ("A 32 bit processes cannot access modules of a 64 bit process") when run from a 32-bit application when the active process is 64-bit.

编辑:作为达明指出,这code是容易出现竞争情况,因为在当时的活动窗口的过程中,当 GetForegroundWindow()被称为可能不存在了,当 GetWindowThreadProcessId()被调用。更糟糕的情况是,如果同样的HWND将被分配到当时的另一个窗口,但我想这应该是真难得。

As Damien pointed out, this code is prone to race conditions, because the process that had the active window at the time when GetForegroundWindow() was called might not exist anymore when GetWindowThreadProcessId() is called. Even worse situation would be if the same hwnd would be assigned to another window at that time, but I guess this should be really rare.

这篇关于如何获得在C#活动过程名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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