天天看點

在delphi中生成GUID

什麼是 GUID ?

全球唯一辨別符 (GUID) 是一個字母數字辨別符,用于訓示産品的唯一性安裝。在許多流行軟體應用程式(例如 Web 浏覽器和媒體播放器)中,都使用 GUID。

GUID 的格式為8-4-4-4-12 :“xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx”其中每個 x 是 0-9 或 A-F 範圍内的一個十六進制的數字。例如:6F9619FF-8B86-D011-B42D-00C04FC964FF 即為有效的 GUID 值。

為什麼要使用 GUID ?

世界上的任何兩台計算機都不會生成重複的 GUID 值。GUID 主要用于在擁有多個節點、多台計算機的網絡或系統中,配置設定必須具有唯一性的辨別符。資料庫中用作主鍵,辨別唯一且在不同的資料庫之間轉換資料不會出錯,而用自增字段就會有很多麻煩。在 Windows 平台上,GUID 應用非常廣泛:系統資料庫、類及接口辨別、資料庫、甚至自動生成的機器名、目錄名等。

Delphi中如何生成GUID:

// uses ComObj
function getGUID():string;
 var
  sGUID: string;
begin
  sGUID := CreateClassID;
  //ShowMessage(sGUID); // 兩邊帶大括号的Guid
  Delete(sGUID, 1, 1);
  Delete(sGUID, Length(sGUID), 1);
  //ShowMessage(sGUID); // 去掉大括号的Guid,占36位中間有減号
  sGUID:= StringReplace(sGUID, '-', '', [rfReplaceAll]);
  //ShowMessage(sGUID); // 去掉減号的Guid,占32位
  result:=sGUID;
end;
           

生成GUID的算法根據以下幾個方面:1.目前日期與時間。2.網卡位址。3.時針序。4.自動遞增計數器。其中,網卡位址是互相不同的,對沒有網卡的機器,自動遞增計數器對使用中的機器保持唯一性,MS保證同一台電腦中每秒生成100個GUID在3000多年内一個GUID是絕對唯一的.

Delphi做的程式,如果想包含版本資訊, 必須在Delphi的內建編輯環境的菜單“Project/Options/Version Info”裡面添加版本資訊。即在Version Info 頁籤中選中“Include version information in project”項,并在“Module version number”中設定Major version(主版本号)、 Minor version(副版本号)、 Release(發行版本号)、 Build(内部版本号)。

  設定好後,在程式中寫入下面的函數:

function GetBuildInfo: string; //擷取版本号

var

 verinfosize : DWORD;

 verinfo : pointer;

 vervaluesize : dword;

 vervalue : pvsfixedfileinfo;

 dummy : dword;

 v1,v2,v3,v4 : word;

begin

 verinfosize := getfileversioninfosize(pchar(paramstr(0)),dummy);

 if verinfosize = 0 then begin

  dummy := getlasterror;

  result := '0.0.0.0';

 end;

 getmem(verinfo,verinfosize);

 getfileversioninfo(pchar(paramstr(0)),0,verinfosize,verinfo);

 verqueryvalue(verinfo,'\',pointer(vervalue),vervaluesize);

 with vervalue^ do begin

  v1 := dwfileversionms shr 16;

  v2 := dwfileversionms and $ffff;

  v3 := dwfileversionls shr 16;

  v4 := dwfileversionls and $ffff;

 end;

 result := inttostr(v1) + '.' + inttostr(v2) + '.' + inttostr(v3) + '.' + inttostr(v4);

 freemem(verinfo,verinfosize);

end;

  //然後,在程式中調用函數即可。

procedure TForm1.FormCreate(Sender: TObject);

begin

 label1.Caption := '版本 ' + GetBuildInfo;

end;
           

繼續閱讀