在VB中调用CoCreateGUID创建GUID字符串


Option Explicit
  Private Type GUIDType
          D1               As Long
          D2               As Integer
          D3               As Integer
          D4(8)         As Byte
  End Type
  Private Declare Function WinCoCreateGuid Lib "OLE32.DLL" Alias "CoCreateGuid" (g As GUIDType) As Long
  Public Function CreateGUIDString() As String
          Dim g     As GUIDType
          Dim sBuf     As String
          Call WinCoCreateGuid(g)
          sBuf = PadZeros(Hex$(g.D1), 8, True) & _
                  PadZeros(Hex$(g.D2), 4, True) & _
                  PadZeros(Hex$(g.D3), 4, True) & _
                  PadZeros(Hex$(g.D4(0)), 2) & _
                  PadZeros(Hex$(g.D4(1)), 2, True) & _
                  PadZeros(Hex$(g.D4(2)), 2) & _
                  PadZeros(Hex$(g.D4(3)), 2) & _
                  PadZeros(Hex$(g.D4(4)), 2) & _
                  PadZeros(Hex$(g.D4(5)), 2) & _
                  PadZeros(Hex$(g.D4(6)), 2) & _
                  PadZeros(Hex$(g.D4(7)), 2)
          CreateGUIDString = sBuf
  End Function
  
  Private Function PadZeros(ByVal sBit As String, _
          ByVal iStrLen As Integer, Optional bHyphen _
          As Boolean) As String
          If iStrLen > Len(sBit) Then
                  sBit = Right$(String$((iStrLen - Len(sBit)), _
                          "0") & sBit, iStrLen)
          End If
          If bHyphen Then sBit = sBit & "-"
          PadZeros = sBit
  End Function
Private Sub Command1_Click()
List1.AddItem CreateGUIDString
End Sub
 

你可能感兴趣的:(原创)