一招教你轻松用Delphi检测Windows操作系统版本号

2026-11-13 0 阅读

在Delphi编程中,检测Windows操作系统的版本号是一个常见的需求。通过正确的方法,我们可以轻松地获取到当前操作系统的详细信息,比如它的版本、构建号等。以下是一篇详细的指南,将教你如何使用Delphi编写代码来检测Windows操作系统版本号。

1. 使用Windows API

在Delphi中,我们可以通过调用Windows API来获取操作系统的版本信息。以下是一个简单的示例,展示如何使用GetVersionEx函数来获取版本信息。

1.1 包含必要的单元

首先,确保在你的Delphi项目中包含了Windows和SysUtils单元。

uses
  Windows, SysUtils;

1.2 定义版本结构

定义一个结构来存储版本信息。

type
  TOSVersionInfo = record
    dwOSVersionInfoSize: DWORD;
    dwMajorVersion: DWORD;
    dwMinorVersion: DWORD;
    dwBuildNumber: DWORD;
    dwPlatformId: DWORD;
    szCSDVersion: array [0..31] of Char;
  end;

1.3 获取版本信息

使用GetVersionEx函数来填充上述结构。

function GetWindowsVersion: TOSVersionInfo;
var
  VersionInfo: TOSVersionInfo;
begin
  VersionInfo.dwOSVersionInfoSize := SizeOf(TOSVersionInfo);
  if GetVersionEx(@VersionInfo) then
    Result := VersionInfo
  else
    Result := TOSVersionInfo.Create;
end;

1.4 使用示例

以下是如何使用上述函数来获取并显示版本信息。

var
  VersionInfo: TOSVersionInfo;
begin
  VersionInfo := GetWindowsVersion;
  Writeln('Major Version: ', VersionInfo.dwMajorVersion);
  Writeln('Minor Version: ', VersionInfo.dwMinorVersion);
  Writeln('Build Number: ', VersionInfo.dwBuildNumber);
end;

2. 使用TWindowsVersion类

Delphi的VCL中提供了一个名为TWindowsVersion的类,可以直接使用来获取Windows版本信息。

2.1 使用TWindowsVersion类

uses
  Windows, SysUtils, Vcl.WindowsVersion;

procedure ShowWindowsVersion;
var
  Version: TWindowsVersion;
begin
  Version := TWindowsVersion.Create;
  try
    Writeln('Major Version: ', Version.MajorVersion);
    Writeln('Minor Version: ', Version.MinorVersion);
    Writeln('Build Number: ', Version.BuildNumber);
  finally
    Version.Free;
  end;
end;

3. 总结

通过上述方法,你可以轻松地在Delphi中获取Windows操作系统的版本信息。无论是使用Windows API还是VCL类,都可以帮助你快速地实现这一功能。希望这篇指南能够帮助你更好地理解如何在Delphi中检测Windows操作系统版本号。

分享到: