取得電腦名稱

使用API

API名稱:GetComputerName
動態連結程式庫: kernel32.dll


程式說明

取得電腦目前電腦名稱。
如更改電腦名稱,須重開機才能取得新的電腦名稱。


VB6程式碼

Private Declare Function GetComputerName Lib "kernel32" Alias _
    "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Dim buffer As String * 512, length As Long

Private Sub Command1_Click()
    length = Len(buffer)
    If GetComputerName(buffer, length) Then
        ' Returns nonzero if successful, and modifies the length argument
    Text1.Text = "Computer Name = " & Left$(buffer, length)
    End If
End Sub

VB.NET程式碼

Imports System.ComponentModel
Imports System.Runtime.InteropServices
Imports System.Text

Public Class Form1
    <DllImport("kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
    Private Shared Function GetComputerNameW(ByVal lpBuffer As StringBuilder, ByRef lpnSize As Integer) As Integer
    End Function

    Dim buffer As StringBuilder = New StringBuilder(512)
    Dim length As Long = 512

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If GetComputerNameW(buffer, length) Then
            ' Returns nonzero if successful, and modifies the length argument
            TextBox1.Text = buffer.ToString
        End If
    End Sub
End Class

下載