Generating a UUID in Delphi is straightforward thanks to the RTL (Runtime Library) functions provided by Delphi. Here's how you can generate a UUID (or GUID, as it is often referred to in Windows programming) in Delphi:
Basic UUID Generation in Delphi
You can use the CreateGUID
function from the SysUtils
unit to generate a UUID. Here is a simple example:
program GenerateUUID;
{$APPTYPE CONSOLE}
uses
SysUtils;
var
Guid: TGUID;
GuidString: string;
begin
try
// Generate a new UUID
if CreateGUID(Guid) = S_OK then
begin
// Convert the UUID to string format
GuidString := GUIDToString(Guid);
// Output the generated UUID
WriteLn('Generated UUID: ' + GuidString);
end
else
WriteLn('Failed to generate UUID.');
except
on E: Exception do
WriteLn(E.ClassName, ': ', E.Message);
end;
end.
Explanation
CreateGUID(Guid)
: This function generates a new GUID and stores it in theGuid
variable. It returnsS_OK
if successful.GUIDToString(Guid)
: This function converts the GUID to its string representation in the standard format (e.g.,{123e4567-e89b-12d3-a456-426614174000}
).
Running the Code
- Create a new console application in your Delphi IDE.
- Copy and paste the code above into your main project file.
- Run the application to see the generated UUID printed to the console.
Output Example
When you run the code, the output will be similar to:
Generated UUID: {123E4567-E89B-12D3-A456-426614174000}
Each time you run the program, a different UUID will be generated.
Additional Formatting
If you need the UUID in a different format, you can manipulate the string representation of the GUID. Here are some examples:
Remove Braces
GuidString := StringReplace(GUIDToString(Guid), '{', '', [rfReplaceAll]);
GuidString := StringReplace(GuidString, '}', '', [rfReplaceAll]);
WriteLn('UUID without braces: ' + GuidString);
Convert to Uppercase
GuidString := UpperCase(GUIDToString(Guid));
WriteLn('UUID in uppercase: ' + GuidString);
Convert to Lowercase
GuidString := LowerCase(GUIDToString(Guid));
WriteLn('UUID in lowercase: ' + GuidString);
These additional formatting options allow you to customize the UUID string to match the requirements of your application.