|
|
#1 | |
|
Hyperactive Member
Join Date: Sep 05
Posts: 344
![]() |
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.NET 2005 I declare this API like this: Code:
Private Declare Function GetCaretBlinkTime Lib "user32.dll" () As Int32 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
Code:
<DllImport("user32", EntryPoint:="GetCaretBlinkTime", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Function GetCaretBlinkTime() As Int32
End Function
Quote:
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. |
|
|
|
|
|
|
#2 |
|
.NUT
Join Date: May 05
Location: Sydney, Australia
Posts: 54,913
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() |
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.
__________________
![]() 2007, 2008, 2009, 2010 Why is my data not saved to my database? | Communicating between multiple forms | MSDN Data Walkthroughs MSDN "How Do I?" Videos: VB | C# VBForums Database Development FAQ My CodeBank Submissions: VB | C# (ForumAccount has translated some of my VB submissions to C#) My Blog: Defining and Raising Custom Events | Manipulating GDI+ Drawings | Using Parameters in ADO.NET |
|
|
|
|
|
#3 |
|
Hyperactive Member
Join Date: Sep 05
Posts: 344
![]() |
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
|
|
|
|
![]() |
|
||||||
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | Search this Thread |
| Display Modes | |
|
|