Obtain Process ID using .NET and API Calls

  • Thread starter Thread starter Frank DeLuccia
  • Start date Start date
F

Frank DeLuccia

Hello All,

I was wondering how to call API functions within .NET. I'm getting:

An unhandled exception of type
'System.Runtime.InteropServices.MarshalDirectiveException' occurred in
WindowsApplication1.exe
Additional information: PInvoke restriction: can not return variants.

when running this code:

Declare Function GetWindowThreadProcessID Lib "user32" (ByVal hwnd As Long,
ByVal lpdwProcessID As Long)
************************************************************
Dim objExcel As New Excel.ApplicationClass()
Dim lngProcessID As Long
Dim lngHwnd As Long

With objExcel
lngHwnd = .Hwnd
GetWindowThreadProcessID(lngHwnd, lngProcessID) <---- error occurs
.Quit()
End With

I have no clue why this is happening. Any ideas or guidance would be
greatly appreciated.

Thanks,
Frank
 
Frank,
Declare Function GetWindowThreadProcessID Lib "user32" (ByVal hwnd As Long,
ByVal lpdwProcessID As Long)

- Turn on Option Strict
- Change the declaration to

Declare Function GetWindowThreadProcessID Lib "user32" (ByVal hwnd As
IntPtr, ByRef lpdwProcessID As Integer) As Integer



Mattias
 
Frank said:
Declare Function GetWindowThreadProcessID Lib "user32" (ByVal hwnd As
Long, ByVal lpdwProcessID As Long)

You missed an "as System.UInt32"

And the correct definition is (for C#):
[DllImport("user32.dll")]
static extern uint GetWindowThreadProcessId(IntPtr hWnd,
out IntPtr lpdwProcessId);

For more info see www.pinvoke.net

--
Greetings
Jochen

Do you need a memory-leak finder ?
http://www.codeproject.com/tools/leakfinder.asp

Do you need daily reports from your server?
http://sourceforge.net/projects/srvreport/
 
Thanks for the response! I changed the declaration as instructed and now
I'm getting this:

An unhandled exception of type 'System.EntryPointNotFoundException' occurred
in WindowsApplication1.exe

Additional information: Unable to find an entry point named
GetWindowThreadProcessID in DLL user32.

Here is the change:
Option Strict On

Declare Function GetWindowThreadProcessID Lib "user32" (ByVal hwnd As
IntPtr, ByRef lpdwProcessID As Integer) As Integer

*********************************************************

Dim objExcel As New Excel.ApplicationClass()
Dim objPtr As IntPtr
Dim intID As Integer

With objExcel
objPtr = New IntPtr(objExcel.Hwnd)
GetWindowThreadProcessID(objPtr, intID) <---- Fails
End With


Thanks again for your time,
Frank
 
Frank,
Declare Function GetWindowThreadProcessID Lib "user32" (ByVal hwnd As
IntPtr, ByRef lpdwProcessID As Integer) As Integer

The function name should en with Id, not ID. Yes, Win32 entry points
are case sensitive. Sorry I missed that before.



Mattias
 
Back
Top