什么是GUID?GUID是Globally Unique IDentifier的缩写.由一个特殊的算法来产生这些128位的数,并保证不产生重复的GUID—重复的可能性当然存在,但有太多可用的数了,因此算法特别防止产生重复的数,这种情况你一生都不会看到.
ActiveX控件都有一个用于相互区别的GUID.你如何在自己的程序中使用GUID呢? 例如,当一个数据库的每个条目都需要由一个唯一的键值时.下面的代码将给你一个答案:
向窗体frmTest中放置一个名为cmdGUID的按钮和一个名为txtGUID的文本框,加入一下代码:
Option Explicit
Private Type GUID
Data1 As Long
Data2 As Long
Data3 As Long
Data4(8) As Byte
End Type
Private Declare Function CoCreateGuid Lib "ole32.dll" (pguid As GUID)
As Long
Private Declare Function StringFromGUID2 Lib "ole32.dll"(rguid As Any,ByVal
lpstrClsId As Long,ByVal cbMax As Long) As Long
Private Function GUIDGen() As String
Dim uGUID As GUID
Dim sGUID As String
Dim bGUID() As Byte
Dim lLen As Long
Dim RetVal As Long
lLen = 40
bGUID = String(lLen, 0)
CoCreateGuid uGUID ’把结构转换为一个可显示的字符串
RetVal = StringFromGUID2(uGUID, VarPtr(bGUID(0)), lLen)
sGUID = bGUID
If (Asc(Mid$(sGUID, RetVal, 1)) = 0) Then RetVal = RetVal - 1
GUIDGen = Left$(sGUID, RetVal)
End Function
Private Sub cmdGUID_Click()
txtGUID.Text = GUIDGen
End Sub
运行程序.
每次点击按钮,文本框中都会出现一个不同的数值. 你可能要点上无数年才会看到一个重复的数值.