Windows APIs
大多数的API调用可以象在Visual Basic 6.0中一样使用,因为
数据类型发生了改变。在Visual Basic 6.0中的Long类型在Visual Basic.NET中定义为Integer类型。在升级过程中这些定义会自动改变,例如:
Private Declare Function GetVersion Lib "kernel32" () As
Long
Function GetVer()
Dim Ver As Long
Ver = GetVersion()
MsgBox ("System Version is " & Ver)
End Function
改变为:
Private Declare Function GetVersion Lib "kernel32" () As
Integer
Function GetVer()
Dim Ver As Integer
Ver = GetVersion()
MsgBox("System Version is " & Ver)
End Function
除了数字类型的升级外,Visual Basic 6.0还支持固定长度字符
串类型,该类型升级到Visual Basic.NET后会定义为固定长度字符串兼容类。
所以在Visual Basic 6.0代码中最好使用通用字符串定义,例如:
Private Declare Function GetUserName Lib "advapi32.dll"
Alias _
"GetUserNameA" (ByVal lpBuffer As String, ByRef nSize As
Long) As Long
Function GetUser()
Dim Ret As Long
Dim UserName As String
Dim Buffer As String * 25
Ret = GetUserName(Buffer, 25)
UserName = Left$(Buffer, InStr(Buffer, Chr(0)) - 1)
MsgBox (UserName)
End Function
上面的代码出现了固定长度字符串,最好更改为:
Dim Buffer As String
Buffer = String$(25, " ")
升级到Visual Basic.NET后会称为下面的样子:
Declare Function GetUserName Lib "advapi32.dll" Alias _
"GetUserNameA" (ByVal lpBuffer As String, ByRef nSize As
Integer) As Integer
Function GetUser()
Dim Ret As Integer
Dim UserName As String
Dim Buffer As String
Buffer = New String(CChar(" "), 25)
Ret = GetUserName(Buffer, 25)
UserName = Left(Buffer, InStr(Buffer, Chr(0)) - 1)
MsgBox(UserName)
End Function
在有些情况下,Visual Basic.NET能够更好的控制传递字符串到
API调用,因为你可以通过ANSI 和UNICODE关键字定义字符串传递的方式。
有三种情况需要对代码最手工改进。
1、在传递给API函数的自定义数据类型定义中包含固定长度字符串和
数组。在Visual Basic.NET中你需要对自定义数据类型定义中的每一个固定长度字符串和数组添加MarshallAs 属性。
2、在定义中使用As Any声明。该种声明不再被Visual Basic.NET支
持,变量定义为As Any通常是为了传递一个既可能是字符串也可能是Null的变量,在Visual Basic.NET中,你可以定义两个不同类型的API,一个为Long类型,一个为String类型,以API函数GetPrivateProfileString 为例:
Private Declare Function GetPrivateProfileString
Lib "kernel32" Alias
"GetPrivateProfileStringA" (ByVal lpApplicationName As
String, ByVal
lpKeyName As Any, ByVal lpDefault As String, ByVal
lpReturnedString As String, ByVal nSize As Long,
ByVal
lpFileName As String) As Long
你可以删除As Any而代之以定义两个不同的函数;一个接受Long数
值,一个接收String树脂:
Private Declare Function GetPrivateProfileStringKey
Lib "kernel32" Alias
"GetPrivateProfileStringA" (ByVal lpApplicationName As
String, ByVal
lpKeyName As String, ByVal lpDefault As String, ByVal
lpReturnedString As String, ByVal nSize As Long,
ByVal
lpFileName As String) As Long
Private Declare Function GetPrivateProfileStringNullKey
Lib "kernel32"
&nbs