Reputation: 5931
Is there a managed VB.net way to get the Process ID from the HWND rather than using this Windows API call.
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
Upvotes: 1
Views: 16278
Reputation: 244981
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.
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):
<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 Process
class. 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 CreateObject
in the first place.
Upvotes: 1