用GetComputerName来获取用户名时,如果处理不好,中文的计算机名则只会显示部分,该计算机名以ASCII码为0的字符结尾。所以我们要去掉这个字符。
Option Explicit Private Const MAX_COMPUTERNAME_LENGTH As Long = 31 Private Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long '************************************************************************* '**函 数 名:GetPCName '**输 入:无 '**输 出:(String) - '**功能描述:获取计算机名 '**作 者:龙轩 '**日 期:2011-08-15 '**版 本:V1.0.0 '************************************************************************* Public Function GetPCName() As String Dim dwLen As Long Dim strString As String Dim strName() As String 'Create a buffer (缓冲区) dwLen = MAX_COMPUTERNAME_LENGTH + 1 strString = String(dwLen, "X") 'Get the computer name GetComputerName strString, dwLen 'get only the actual data strString = Left(strString, dwLen) 'Show the computer name strName = Split(strString, Chr(0)) '由于机器名为汉字时会出错,这里用chr(0)截取一下 GetPCName = strName(0) End Function Private Sub cmdGetPCName_Click() '获取计算机名 MsgBox GetPCName End Sub
效果: