![](/img/trans.png)
[英]What is the best way to have a WinForms application running eternally
[英]What is the best way for a WinForms application to determine exactly which Windows operating system it is running on?
我有一個WinForms應用程序,需要根據運行它的操作系統以特定方式(特別是某個安裝程序的shell)運行。
我正在使用System.OperatingSystem類,並結合使用PlatFormID,Major,Minor和Build數字,這些數字可以幫助您完成大部分工作。
不幸的是,OperatinSystem對象的特性,不允許您在某些平台之間進行精確區分。 例如Vista和Windows Server 2008,或Vista 32位和Vista 64位。 同樣,XP 64位Professional似乎與Server 2003具有相同的版本信息。
那么是否有可能從WinForms應用程序(使用c#)確定您正在運行的Windows操作系統?
區分32位和64位的最簡單方法是通過環境變量PROCESSOR_ARCHITECTURE
。
string value = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
如果您在32位Windows上運行此代碼,則value
將為“x86”或為空。 在64位Windows上我假設它將被設置為“x86”以外的任何東西。 有點亂,但到目前為止它適用於所有可以執行.NET程序的Windows版本。
您還可以使用更現代的WMI來查詢您可以想象的有關操作系統的所有信息,但這只適用於Windows 2000或更高版本。 如果您可以接受, 請查看此博客文章以獲取一些示例 。
您可以使用WMI檢索Win32_OperatingSystem
管理類的信息。
using System;
using System.Management;
using System.Windows.Forms;
namespace WMISample
{
public class MyWMIQuery
{
public static void Main()
{
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_OperatingSystem");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("Win32_OperatingSystem instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("BuildNumber: {0}", queryObj["BuildNumber"]);
Console.WriteLine("Caption: {0}", queryObj["Caption"]);
Console.WriteLine("OSArchitecture: {0}", queryObj["OSArchitecture"]);
Console.WriteLine("OSLanguage: {0}", queryObj["OSLanguage"]);
Console.WriteLine("Version: {0}", queryObj["Version"]);
}
}
catch (ManagementException e)
{
MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
}
}
}
}
這是我一年前為我公司的遺留應用程序所做的事情......我不知道這是最新的方法,但它肯定有效。
If Environment.OSVersion.Platform = PlatformID.Win32NT Then
If major <= 4 Then
ret = "Windows NT 4.0"
_usingNT4 = True
ElseIf major > 6 Then
ret = "Windows Vista"
ElseIf major = 5 And minor = 0 Then
ret = "Windows 2000"
Else
ret = "Windows XP"
End If
Else
If major > 4 Or (major = 4 And minor >= 90) Then
ret = "Windows ME"
ElseIf (major = 4 And minor >= 10 And minor < 90) Then
ret = "Windows 98"
Else
ret = "Windows 95"
End If
End If
如果你真的需要所有的細節,我想你仍然可以使用Win32 API的舊版GetVersionEx 。
事實上,這不是.NET(嚴格來說),但可以在.NET應用程序中使用。 看到這里 。
這是一個更簡單的方法:
string os = Environment.OSVersion.VersionString;
...對於我的操作系統,以上內容返回以下內容:
Microsoft Windows NT 6.1.7600.0
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.