获取给定的运行过程中进程句柄 [英] Get running process given process handle
问题描述
有人可以告诉我,我怎么能在C#中使用过程类,如果我已经知道了手柄捕捉正在运行的进程?
can someone tell me how i can capture a running process in c# using the process class if i already know the handle?
宁愿没有没有枚举在getrunning两种处理方法。 。PInvoke的是确定的,如果可能的。
Id rather not have not have to enumerate the getrunning processes method either. pInvoke is ok if possible.
推荐答案
在纯C#,它看起来像你通过他们都有循环:
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);
上面的例子,如果手柄没有发现故意不。否则,你当然可以使用的SingleOrDefault
。显然,它不喜欢你请求的进程ID 0
,因此额外条件的句柄。
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.
使用该WINAPI,您可以使用 GetProcessId
。我找不到它pinvoke.net,但这应该做的:
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);
(签名使用 DWORD
,但过程ID由 INT
■在.NET基础类库为代表)
(signature uses a DWORD
, but process IDs are represented by int
s in the .NET BCL)
这似乎有点奇怪,你就会有一手柄,但不是然而一个进程ID。进程处理是通过调用 调用OpenProcess $ C $收购C>
,这需要一个过程ID。
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.
这篇关于获取给定的运行过程中进程句柄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!