打印本文 打印本文 关闭窗口 关闭窗口
在VB中获取和修改计算机名字
作者:武汉SEO闵涛  文章来源:敏韬网  点击数654  更新时间:2009/4/23 14:57:54  文章录入:mintao  责任编辑:mintao

 在Win 95中,计算机有一个名字。运行regedit,在“HKEY_LOCAL_MACHINE\System

  \CurrentControlSet\control\ComputerName\ComputerName”中将发现 “ComputerName”

  =“Default”(或其它字符串),在regedit下可以查看和修改这个名字。我们还可在程序

  中通过Win32 API提供的GetComputerName、SetComputerName这两个函数来查看和修改计算机的名字。下面以VB为例来探讨如何编写一个可查看和修改计算机名字的程序。

  1、插入一个新模块,在其中添加如下代码:

  声明GetComputerName

  Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long

  声明SetComputerName

  Declare Function SetComputerName Lib "kernel32" Alias "SetComputerNameA" (ByVal lpComputerName As String) As Long

  ’定义一个获取计算机名字的函数

  Public Function GetCName(CName) As Boolean

  Dim sComputerName As String 计算机的名字

  Dim lComputerNameLen As Long 计算机名字的长度

  Dim lResult As Long GetComputerName的返回值

  Dim RV As Boolean GetCName返回值,若为TRUE则表示操作成功

  lComputerNameLen = 256

  sComputerName = Space(lComputerNameLen)

  lResult = GetComputerName(sComputerName, lComputerNameLen)

  If lResult <> 0 Then

   CName = Left$(sComputerName, lComputerNameLen)

   RV = True

  Else

   RV = False

  End If

  GetCName = RV

  End Function

  定义一个修改计算机名字的函数

  Public Function SetCName(CName As String) 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 "Thi omputer Name is:",CN

  CN="MYCOMPUTER"

  x = SetCName(CN)

  Print "Now the Computer name is:",CN

  End Sub

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

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

打印本文 打印本文 关闭窗口 关闭窗口