GUIDs

From HashVB
Revision as of 16:06, 18 July 2008 by Dee (Talk | contribs)

Jump to: navigation, search
float
 This article is based on Visual Basic 6. Find other Visual Basic 6 articles.

A GUID is a string (or 128bit number), normally used as an ID that is guaranteed to be unique on all machines (assuming they have a network card). They are used as IDs for COM interfaces and classes, database keys and unique IDs for network machines and users.

There are several ways of creating GUIDs but the most common way is to use the CoCreateGuid() function. You can then convert this to a string using the StringFromGUID2() function.

Private Type GUID
  Data1 As Long
  Data2 As Integer
  Data3 As Integer
  Data4(0 To 7) As Byte
End Type

Private Declare Function CoCreateGuid Lib "OLE32.DLL" (pGUID As GUID) As Long
Private Declare Function StringFromGUID2 Lib "OLE32.DLL" (pGUID As GUID, _
  ByVal lpString As Long, ByVal MaxLength As Long) As Long

Public Function CreateGUID() As String
Dim GUID As GUID
Dim GUIDString As String
   
  'Create the GUID
  If CoCreateGuid(GUID) Then
    GUIDString = ""
  Else
    'Pre allocate a string to hold the GUID
    GUIDString = String$(38, 0)
    'Convert to a string
    StringFromGUID2 GUID, StrPtr(GUIDString), 39
  End If
  CreateGUID = GUIDString
End Function