我必须在我的 C# Windows 应用程序中检测 Windows 8 操作系统并进行一些设置。我知道我们可以使用 检测 Windows 7 Environment.OSVersion
,但是如何检测 Windows 8?
提前致谢。
Version win8version = new Version(6, 2, 9200, 0);
if (Environment.OSVersion.Platform == PlatformID.Win32NT &&
Environment.OSVersion.Version >= win8version)
{
// its win8 or higher.
}
好的,在我看来,这段代码已被 Microsoft 本身标记为已弃用。我在这里留下一个链接,这样你就可以阅读更多关于它的信息。
简而言之,它说:
对于 Windows 8 及更高版本,始终会有相同的版本号(6, 2, 9200, 0)。与其寻找 Windows 版本,不如寻找您要解决的实际功能。
Windows 8 或更新版本:
bool IsWindows8OrNewer()
{
var os = Environment.OSVersion;
return os.Platform == PlatformID.Win32NT &&
(os.Version.Major > 6 || (os.Version.Major == 6 && os.Version.Minor >= 2));
}
检查以下问题的答案:如何获得“友好的”操作系统版本名称?
引用答案:
您可以使用 WMI 获取产品名称(“Microsoft® Windows Server® 2008 Enterprise”):
using System.Management;
var name = (from x in new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem").Get().OfType<ManagementObject>() select x.GetPropertyValue("Caption")).First();
return name != null ? name.ToString() : "Unknown";
首先声明一个结构,如下所示:
[StructLayout(LayoutKind.Sequential)]
public struct OsVersionInfoEx
{
public int dwOSVersionInfoSize;
public uint dwMajorVersion;
public uint dwMinorVersion;
public uint dwBuildNumber;
public uint dwPlatformId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string szCSDVersion;
public UInt16 wServicePackMajor;
public UInt16 wServicePackMinor;
public UInt16 wSuiteMask;
public byte wProductType;
public byte wReserved;
}
您将需要这个 using 语句:
using System.Runtime.InteropServices;
在相关类的顶部,声明:
[DllImport("kernel32", EntryPoint = "GetVersionEx")]
static extern bool GetVersionEx(ref OsVersionInfoEx osVersionInfoEx);
现在调用代码如下:
const int VER_NT_WORKSTATION = 1;
var osInfoEx = new OsVersionInfoEx();
osInfoEx.dwOSVersionInfoSize = Marshal.SizeOf(osInfoEx);
try
{
if (!GetVersionEx(ref osInfoEx))
{
throw(new Exception("Could not determine OS Version"));
}
if (osInfoEx.dwMajorVersion == 6 && osInfoEx.dwMinorVersion == 2
&& osInfoEx.wProductType == VER_NT_WORKSTATION)
MessageBox.Show("You've Got windows 8");
}
catch (Exception)
{
throw;
}
不确定这是否正确,因为我只能检查我拥有的 Windows 8 版本。
int major = Environment.OSVersion.Version.Major;
int minor = Environment.OSVersion.Version.Minor;
if ((major >= 6) && (minor >= 2))
{
//do work here
}