VB 程序设计

10个成员

在VB中获取和修改计算机名字

发表于 2016-12-24 2948 次查看
在Win 95中,计算机有一个名字。运行regedit,在“HKEY-LOCAL-MACHINE\System\CurrentControlSet\control\ComputerName\ComputerName”中将发现“ComputerName”=“Default”( 或其它字符串),在regedit下可以查看和修改这个名字。我们还可在程序中通过Win32API提供的GetComputerName、SetComputerName这两个函数来查看和修改计算机的名字。下面以VB为例来探讨如何编写一个可查看和修改计算机名字的程序。

1、 插入一个新模块,在其中添加如下代码:
'声明 GetComputerName
Declare Function GetComputerName Lib "kernel 32" Alias "GetComputerNameA" (Byval lpBuffer As String,nSize As Long)As Long

'声明 SetComputerName
Declare Function SetComputerName Lib "kernel 32" Alias "SetComputerNameA" (Byval lp ComputerName As String)As Long

'定义一个获取计算机名字的函数
Public Function GetCName (CName ) As Boolean
Dim sComputerName As String '计算机的名字
Dim lComputerName As Long '计算机名字的长度
Dim lResult As Long 'GetComputerName的返回值
Dim RV As Boolean

'GetCName返回值,若为TRUE则表示操作成功
lComputerNameLen =256
sComputerName = Space (lComputerNameLen)
lResult =GetComputerName (sComputerName,lCompputerNameLen)
If lResult <>0 Then Cname = Left$ (sComputerName,lComputerNameLen)
RV =True
Else
RV =False
End If
GetCName =RV
End Function

'定义一个修改计算机名字的函数
Public Function SetCName (CName ) As Boolean
Dim lResult As Long
Dim RV As Boolean
lResult =SetComputerName (CName)
If lResult <>0 Then
RV =True 修改成功
Else
RV =False
End If
SetCName =RV
End Function

2、 在窗体中添加一命令按钮Command1,双击该按钮并在其中添加如下代码:

Sub Command1-Click ()
DIM CN AS String
x = GetCName (CN)
Print "This Computer Name is :",CN
CN="MYCOMPUTER"
x = SetCName (CN )
Print "Now the Computer name is :",CN
End Sub

3、 保存上述设置和代码,然后按F5运行该程序,观察其运行结果。

需要说明的是:(1)修改完计算机的名字后必须重新启动才能有效;(2)计算机名字中只能含有字母、数字和下面的几种符号:!、@、#、$、%、^、 ;、'、)、(、· 、- 、{、}、~、(3)程序的运行环境为:VB4.0(32)、Win 95中文版。

 

发表回复
你还没有登录,请先登录注册