Sunday 22 September 2013

How to get computer name using windows API in Visual Basic 6.0

' Platform : any windows OS
' Developing platform visual basic 6.0 (Visual Studio 6.0 IDE)
 '------------------------------------------------------------------------------------------------------------------
option explicit
' GetComputerName is a windows API to retrieve computer name
Private ComputerName as String
Private strBuffer As String
Private lngBufSize As Long
Private lngStatus As Long
private computername as string

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

Private sub Form_Load()

' before passing strBuffer as by reference to "GetComputerName" function, size need to be allocated for strBuffer which is assigned lngBufSize

    lngBufSize = 255  

    strBuffer = String$(lngBufSize, " ") ' Memory allocated for strBuffer

 ' lngStatus returns status for success or failure. return any non zero value for success. computer name is set in the strBuffer string and length of the string is assigned in lngBuffsize, i.e. if  computer name is "subhroneel" then strbuffer is set with "subhroneel" and lngBuffSize is set with 10

    lngStatus = GetComputerName(strBuffer, lngBufSize)

    If lngStatus <> 0 Then
        ' extra allocated space is truncated
        computername = Left(strBuffer, lngBufSize)
    End If

End Sub

No comments: