Get running process given process handle

我怕爱的太早我们不能终老 提交于 2019-12-19 05:48:38

问题


can someone tell me how i can capture a running process in c# using the process class if i already know the handle?

Id rather not have not have to enumerate the getrunning processes method either. pInvoke is ok if possible.


回答1:


In plain C#, it looks like you have to loop through them all:

// IntPtr myHandle = ...
Process myProcess = Process.GetProcesses().Single(
    p => p.Id != 0 && p.Handle == myHandle);

The above example intentionally fails if the handle isn't found. Otherwise, you could of course use SingleOrDefault. Apparently, it doesn't like you requesting the handle of process ID 0, hence the extra condition.

Using the WINAPI, you can use GetProcessId. I couldn't find it on pinvoke.net, but this should do:

[DllImport("kernel32.dll")]
static extern int GetProcessId(IntPtr handle);

(signature uses a DWORD, but process IDs are represented by ints in the .NET BCL)

It seems a bit odd that you'd have a handle, but not a process ID however. Process handles are acquired by calling OpenProcess, which takes a process ID.




回答2:


using System.Diagnostics;

class ProcessHandler {
    public static Process FindProcess( IntPtr yourHandle ) {
        foreach (Process p in Process.GetProcesses()) {
            if (p.Handle == yourHandle) {
                return p;
            }
        }

        return null;
    }
}



回答3:


There seems to be no simple way to do this by the .Net API. The question is, where you got that handle from? If by the same way you can get access to the processes ID, you could use:

Process.GetProcessById (int iD)




回答4:


You could use the GetWindowThreadProcessId WinAPI call

http://www.pinvoke.net/default.aspx/user32/GetWindowThreadProcessId.html

To get the Process Id - then get a Process object using that.....

But why don't you want to enumerate the ids of the running processes?



来源:https://stackoverflow.com/questions/1276629/get-running-process-given-process-handle

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!