[RESOLVED] [2005] VB.NET and APIs
Hello guys!
I just need some clarity on how to properly use APIs in .NET.
In VB 6, we used to declare APIs like this :
Code:
Private Declare Function GetCaretBlinkTime Lib "user32" Alias "GetCaretBlinkTime" () As Long
In VB 2005, I can also declare the same API, almost 100% similar, with the difference being with the function return types, and argument types (Am I correct)
In VB.NET 2005 I declare this API like this:
Code:
Private Declare Function GetCaretBlinkTime Lib "user32.dll" () As Int32
Which is all fine and dandy, BUT, I have noticed many people opting to use the Sytem.Runtime.InteropServices class / namespace (Which is it ?), and then create the particular API like this :
Code:
<DllImport("user32.dll", EntryPoint:="FindWindowEx", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function FindWindowEx(ByVal parentHandle As IntPtr, _
ByVal childAfter As IntPtr, _
ByVal lclassName As String, _
ByVal windowTitle As String) As IntPtr
End Function
I have found this technique amusing. I went ahead and based on the above (FindWindowEx) example, and did this with GetCaretBlinkTime
Code:
<DllImport("user32", EntryPoint:="GetCaretBlinkTime", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Function GetCaretBlinkTime() As Int32
End Function
But, now, I get this error :
Quote:
Originally Posted by Compiler
'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to instance method
Why?
Why can I not follow the same principal as with FindWindowEx?
Can I not use this technique with every API?
Any advice on these will be appreciated.
Re: [2005] VB.NET and APIs
You can use the Declare key word as you did in VB6, but that's a VB hold-over. You need to use numerical types that are as wide as the function expects. Most API functions expect 32-bit numbers. In VB6 that meant Long, but in VB.NET it means Integer.
The "more .NET" way is to use the DllImportAttribute class, which is a member of the System.Runtime.InteropServices namespace. There are a few things you can do with it that are just not possible with Declare.
The reason that code is not working is exactly what the error message says. Imported functions must be declared Shared. The Declare key word inherently creates a Shared method, but with the DllImport attribute you need to specify it yourself.
By the way, MSDN is just a couple of mouse clicks away so there's really no excuse for not knowing what's a class a what's a namespace.
Re: [2005] VB.NET and APIs
Voila!
Code:
<DllImport("user32", EntryPoint:="GetCaretBlinkTime", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function GetCaretBlinkTime() As Int32
End Function
EDIT: Thanx for the reply jmcilhinney, didn't see it upfront. What you said made perfect sense. Thank you!