C# 获取正在运行的进程给定的进程句柄
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1276629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get running process given process handle
提问by Grant
can someone tell me how i can capture a running process in c# using the process class if i already know the handle?
如果我已经知道句柄,有人可以告诉我如何使用进程类在 c# 中捕获正在运行的进程吗?
Id rather not have not have to enumerate the getrunning processes method either. pInvoke is ok if possible.
我也不必枚举 getrunning processes 方法。如果可能,pInvoke 是可以的。
采纳答案by Thorarin
In plain C#, it looks like you have to loop through them all:
在普通的 C# 中,看起来你必须遍历它们:
// 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.
如果未找到句柄,则上面的示例故意失败。否则,您当然可以使用SingleOrDefault
. 显然,它不喜欢你请求进程 ID 的句柄0
,因此有额外的条件。
Using the WINAPI, you can use GetProcessId
. I couldn't find it on pinvoke.net, but this should do:
使用 WINAPI,您可以使用GetProcessId
. 我在 pinvoke.net 上找不到它,但这应该可以:
[DllImport("kernel32.dll")]
static extern int GetProcessId(IntPtr handle);
(signature uses a DWORD
, but process IDs are represented by int
s in the .NET BCL)
(签名使用DWORD
,但进程 IDint
在 .NET BCL 中由s表示)
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.
你有一个句柄,但没有进程 ID,这似乎有点奇怪。进程句柄是通过调用OpenProcess
获取进程 ID 的。
回答by RaYell
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;
}
}
回答by Frank Bollack
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:
.Net API 似乎没有简单的方法可以做到这一点。问题是,你从哪里得到这个句柄?如果您可以通过同样的方式访问进程 ID,则可以使用:
Process.GetProcessById (int iD)
Process.GetProcessById (int iD)
回答by Mesh
You could use the GetWindowThreadProcessId WinAPI call
您可以使用 GetWindowThreadProcessId WinAPI 调用
http://www.pinvoke.net/default.aspx/user32/GetWindowThreadProcessId.html
http://www.pinvoke.net/default.aspx/user32/GetWindowThreadProcessId.html
To get the Process Id - then get a Process object using that.....
要获取进程 ID - 然后使用它获取进程对象.....
But why don't you want to enumerate the ids of the running processes?
但是为什么不想枚举正在运行的进程的 ID?