vb.net调用api函数GetComputerName,内存出错。解决思路
vb.net调用api函数GetComputerName,内存出错。
代码如下:
Public Class Form2
Private Const MAX_COMPUTERNAME_LENGTH As Long = 31
Private Declare Function GetComputerName Lib "kernel32 " Alias "GetComputerNameA " (ByVal lpBuffer As String, ByVal nSize As Long) As Long
Private Sub Form2_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim dwLen As Long
Dim strString As String
Dim i As Long
'Create a buffer
dwLen = MAX_COMPUTERNAME_LENGTH + 1
strString = New String( " ", dwLen)
'Get the computer name
i = GetComputerName(strString, dwLen)
'get only the actual data
strString = strString.Substring(0, dwLen)
'Show the computer name
MsgBox(strString)
End Sub
End Class
一运行到 {i = GetComputerName(strString, dwLen)} 就报告内存读写异常。在网上搜索,也没有找到解决办法,希望大家帮忙。
------解决方案--------------------
用来获得本机机器名的话,可以用
Dim HostName As String = System.Net.Dns.GetHostName '获得本机的机器名
不知道这个函数在.NET下是否还支持,但是.NET中的Integer是32位的相当于6.0中的Long,所以在声明是要把原来的Long,都替换为integer或int32,即
Private Const MAX_COMPUTERNAME_LENGTH As Integer = 31
Private Declare Function GetComputerName Lib "kernel32 " Alias "GetComputerNameA " (ByVal lpBuffer As String, ByVal nSize As Integer) As Integer
在调用时也要做相应的改变。
------解决方案--------------------
2005直接使用期 pc_jsjm = My.Computer.Name Vb.net
代码如下:
Public Class Form2
Private Const MAX_COMPUTERNAME_LENGTH As Long = 31
Private Declare Function GetComputerName Lib "kernel32 " Alias "GetComputerNameA " (ByVal lpBuffer As String, ByVal nSize As Long) As Long
Private Sub Form2_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim dwLen As Long
Dim strString As String
Dim i As Long
'Create a buffer
dwLen = MAX_COMPUTERNAME_LENGTH + 1
strString = New String( " ", dwLen)
'Get the computer name
i = GetComputerName(strString, dwLen)
'get only the actual data
strString = strString.Substring(0, dwLen)
'Show the computer name
MsgBox(strString)
End Sub
End Class
一运行到 {i = GetComputerName(strString, dwLen)} 就报告内存读写异常。在网上搜索,也没有找到解决办法,希望大家帮忙。
------解决方案--------------------
用来获得本机机器名的话,可以用
Dim HostName As String = System.Net.Dns.GetHostName '获得本机的机器名
不知道这个函数在.NET下是否还支持,但是.NET中的Integer是32位的相当于6.0中的Long,所以在声明是要把原来的Long,都替换为integer或int32,即
Private Const MAX_COMPUTERNAME_LENGTH As Integer = 31
Private Declare Function GetComputerName Lib "kernel32 " Alias "GetComputerNameA " (ByVal lpBuffer As String, ByVal nSize As Integer) As Integer
在调用时也要做相应的改变。
------解决方案--------------------
2005直接使用期 pc_jsjm = My.Computer.Name Vb.net