如何使用托管的 VB.net 代码从 HWND 获取进程 ID?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17778414/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 14:19:56  来源:igfitidea点击:

How do I get Process ID from HWND using managed VB.net code?

vb.net

提问by D_Bester

Is there a managed VB.net way to get the Process ID from the HWND rather than using this Windows API call.

是否有一种托管的 VB.net 方法可以从 HWND 获取进程 ID,而不是使用此 Windows API 调用。

Private Declare Auto Function GetWindowThreadProcessId Lib "user32.dll" (ByVal hwnd As IntPtr, _
              ByRef lpdwProcessId As Integer) As Integer

Sub GetProcessID()

    'start the application
    Dim xlApp As Object = CreateObject("Excel.Application")

    'get the window handle
    Dim xlHWND As Integer = xlApp.hwnd

    'this will have the process ID after call to GetWindowThreadProcessId
    Dim ProcIdXL As Integer = 0

    'get the process ID
    GetWindowThreadProcessId(xlHWND, ProcIdXL)

    'get the process
    Dim xproc As Process = Process.GetProcessById(ProcIdXL)

End Sub

采纳答案by Cody Gray

No, this isn't wrapped by .NET. But there's absolutely nothing wrong with calling the native API functions. That's what the framework does internally, and that's why P/Invoke was invented, to make it as simple as possible for you to do this yourself. I'm not really sure why you're seeking to avoid it.

不,这不是由 .NET 包装的。但是调用原生 API 函数绝对没有错。这就是框架在内部所做的事情,这就是为什么要发明 P/Invoke,让您自己做这件事尽可能简单。我不确定你为什么要避免它。

Of course, I would recommend using the new-style declaration, which is the more idiomatic way of doing things in .NET (rather than the old VB 6 way):

当然,我会推荐使用新式声明,这是在 .NET 中更惯用的做事方式(而不是旧的 VB 6 方式):

<DllImport("user32.dll", SetLastError:=True)> _
Private Shared Function GetWindowThreadProcessId(ByVal hWnd As IntPtr, _
    ByRef lpdwProcessId As Integer) As Integer
End Function

Your other option, if you absolutely cannot get over the irrational compulsion to stay with managed code, is to make use of the Processclass. This can be used to start an external process, and has a property (Id) that can be used to retrieve the process's ID. I'm not sure if that will work for you. You specifically avoid telling us why you're using CreateObjectin the first place.

如果您绝对无法克服使用托管代码的非理性强迫,您的另一种选择是使用Process该类。这可用于启动外部进程,并具有Id可用于检索进程 ID的属性 ( )。我不确定这是否适合你。您一开始就特别避免告诉我们您使用的原因CreateObject