在C#下获得操作系统是windows xp professional还是windows xp home

       在VS.NET中,通常使用Version.Minor或者System.Environment.OSVersion.ToString()来获得关于操作系统信息的情况,这有一个例外(也许是我还不知道怎么用),即只能获得xp or nt,98之类,以及一些版本号。无法获得是windows xp professional或者windows xp home。
        如果在DELPHI或者VC下,这问题不复杂,很简单,用API直接搞定。使用GetVersionEx传递如下结构来获得此信息
typedef struct _OSVERSIONINFOEX {
 DWORD dwOSVersionInfoSize; 
DWORD dwMajorVersion;
 DWORD dwMinorVersion;
 DWORD dwBuildNumber;
 DWORD dwPlatformId; 
TCHAR szCSDVersion[128]; 
WORD wServicePackMajor;
 WORD wServicePackMinor; 
WORD wSuiteMask;  //此成员可以用来作为判断home 还是professional的依据
BYTE wProductType;
 BYTE wReserved;
} OSVERSIONINFOEX, *POSVERSIONINFOEX, *LPOSVERSIONINFOEX;

注意是此结构,而不是那个仅有此结构前6个成员的。

       那天晚上无事,在C#板块看到这么一个问题,用C#给他写示例代码,因为对C#的一些机制还不是很熟悉,例如在C#中调用API,以及公共语言运行库利用structlayoutattribute控制类或结构的数据字段在托管内存中的物理布局,即类或结构需要按某种方式排列,结果一边查资料,一边搞。搞了2个多小时,失败啊。
   关于获得操作系统信息,到处都是例子,此文更多的记录下C#下调用API的东西,关于操作系统的判断,可以参考http://msdn2.microsoft.com/en-us/library/ms724429.aspx
 

转载的一个关于C#中调用WIN API的要点,转载自【站长天空 -> 网络办公】,内容如下:
一、调用格式
using system.runtime.interopservices; //引用此名称空间,简化后面的代码
...
//使用dllimportattribute特性来引入api函数,注意声明的是空方法,即方法体为空。
[dllimport("user32.dll")]
public static extern returntype functionname(type arg1,type arg2,...);
//调用时与调用其他方法并无区别

可以使用字段进一步说明特性,用逗号隔开,如:
[ dllimport( "kernel32", entrypoint="getversionex" )]
dllimportattribute特性的公共字段如下:
1、callingconvention 指示向非托管实现传递方法参数时所用的 callingconvention 值。
callingconvention.cdecl : 调用方清理堆栈。它使您能够调用具有 varargs 的函数。
callingconvention.stdcall : 被调用方清理堆栈。它是从托管代码调用非托管函数的默认约定。
2、charset 控制调用函数的名称版本及指示如何向方法封送 string 参数。
此字段被设置为 charset 值之一。如果 charset 字段设置为 unicode,则所有字符串参数在传递到非托管实现之前都转换成 unicode 字符。这还导致向 dll entrypoint 的名称中追加字母“w”。如果此字段设置为 ansi,则字符串将转换成 ansi 字符串,同时向 dll entrypoint 的名称中追加字母“a”。大多数 win32 api 使用这种追加“w”或“a”的约定。如果 charset 设置为 auto,则这种转换就是与平台有关的(在 windows nt 上为 unicode,在 windows 98 上为 ansi)。charset 的默认值为 ansi。charset 字段也用于确定将从指定的 dll 导入哪个版本的函数。charset.ansi 和 charset.unicode 的名称匹配规则大不相同。对于 ansi 来说,如果将 entrypoint 设置为“mymethod”且它存在的话,则返回“mymethod”。如果 dll 中没有“mymethod”,但存在“mymethoda”,则返回“mymethoda”。对于 unicode 来说则正好相反。如果将 entrypoint 设置为“mymethod”且它存在的话,则返回“mymethodw”。如果 dll 中不存在“mymethodw”,但存在“mymethod”,则返回“mymethod”。如果使用的是 auto,则匹配规则与平台有关(在 windows nt 上为 unicode,在 windows 98 上为 ansi)。如果 exactspelling 设置为 true,则只有当 dll 中存在“mymethod”时才返回“mymethod”。

3、entrypoint 指示要调用的 dll 入口点的名称或序号。
如果你的方法名不想与api函数同名的话,一定要指定此参数,例如:
[dllimport("user32.dll",charset="charset.auto",entrypoint="messagebox")]
public static extern int msgbox(intptr hwnd,string txt,string caption, int type);

4、exactspelling 指示是否应修改非托管 dll 中的入口点的名称,以与 charset 字段中指定的 charset 值相对应。如果为 true,则当 dllimportattribute.charset 字段设置为 charset 的 ansi 值时,向方法名称中追加字母 a,当 dllimportattribute.charset 字段设置为 charset 的 unicode 值时,向方法的名称中追加字母 w。此字段的默认值是 false。
5、preservesig 指示托管方法签名不应转换成返回 hresult、并且可能有一个对应于返回值的附加 [out, retval] 参数的非托管签名。
6、setlasterror 指示被调用方在从属性化方法返回之前将调用 win32 api setlasterror。 true 指示调用方将调用 setlasterror,默认为 false。运行时封送拆收器将调用 getlasterror 并缓存返回的值,以防其被其他 api 调用重写。用户可通过调用 getlastwin32error 来检索错误代码。

二、参数类型:
1、数值型直接用对应的就可。(dword -> int , word -> int16)
2、api中字符串指针类型 -> .net中string
3、api中句柄 (dword) -> .net中intptr
4、api中结构 -> .net中结构或者类。注意这种情况下,要先用structlayout特性限定声明结构或类
公共语言运行库利用structlayoutattribute控制类或结构的数据字段在托管内存中的物理布局,即类或结构需要按某种方式排列。如果要将类传递给需要指定布局的非托管代码,则显式控制类布局是重要的。它的构造函数中用layoutkind值初始化 structlayoutattribute 类的新实例。 layoutkind.sequential 用于强制将成员按其出现的顺序进行顺序布局。
layoutkind.explicit 用于控制每个数据成员的精确位置。利用 explicit, 每个成员必须使用 fieldoffsetattribute 指示此字段在类型中的位置。如:

[structlayout(layoutkind.explicit, size=16, charset=charset.ansi)] 
public class mysystemtime 

[fieldoffset(
0)]public ushort wyear; 
[fieldoffset(
2)]public ushort wmonth; 
[fieldoffset(
4)]public ushort wdayofweek; 
[fieldoffset(
6)]public ushort wday; 
[fieldoffset(
8)]public ushort whour; 
[fieldoffset(
10)]public ushort wminute; 
[fieldoffset(
12)]public ushort wsecond; 
[fieldoffset(
14)]public ushort wmilliseconds; 
}
 

下面是针对api中osversioninfo结构,在.net中定义对应类或结构的例子:
/**********************************************
* api中定义原结构声明
* osversioninfoa struct
* dwosversioninfosize dword ?
* dwmajorversion dword ?
* dwminorversion dword ?
* dwbuildnumber dword ?
* dwplatformid dword ?
* szcsdversion byte 128 dup (?)
* osversioninfoa ends
*
* osversioninfo equ <osversioninfoa>
*********************************************/

//.net中声明为类
      此例中用到mashalas特性,它用于描述字段、方法或参数的封送处理格式。用它作为参数前缀并指定目标需要的数据类型。例如,以下代码将两个参数作为数据类型长指针封送给 windows api 函数的字符串 (lpstr):
[marshalas(unmanagedtype.lpstr)]
string existingfile;
[marshalas(unmanagedtype.lpstr)]
string newfile;

[ structlayout( layoutkind.sequential )] 
public class osversioninfo 

public int osversioninfosize; 
public int majorversion; 
public int minorversion; 
public int buildnumber; 
public int platformid; 

[ marshalas( unmanagedtype.byvaltstr, sizeconst
=128 )] 
public string versionstring; 
}
 


//或者
//.net中声明为结构

[ structlayout( layoutkind.sequential )] 
public struct osversioninfo2 

public int osversioninfosize; 
public int majorversion; 
public int minorversion; 
public int buildnumber; 
public int platformid; 

[ marshalas( unmanagedtype.byvaltstr, sizeconst
=128 )] 
public string versionstring; 
}
 

 

      注意结构作为参数时候,一般前面要加上ref修饰符,否则会出现错误:对象的引用没有指定对象的实例。
[ dllimport( "kernel32", entrypoint="getversionex" )]
public static extern bool getversionex2( ref osversioninfo2 osvi );

三、如何保证使用托管对象的平台调用成功?
如果在调用平台 invoke 后的任何位置都未引用托管对象,则垃圾回收器可能将完成该托管对象。这将释放资源并使句柄无效,从而导致平台invoke 调用失败。用 handleref 包装句柄可保证在平台 invoke 调用完成前,不对托管对象进行垃圾回收。
例如下面:
filestream fs = new filestream( "a.txt", filemode.open );
stringbuilder buffer = new stringbuilder( 5 );
int read = 0;
readfile(fs.handle, buffer, 5, out read, 0 ); //调用win api中的readfile函数
由于fs是托管对象,所以有可能在平台调用还未完成时候被垃圾回收站回收。将文件流的句柄用handleref包装后,就能避免被垃圾站回收:

[ dllimport( "kernel32.dll" )] 
public static extern bool readfile( 
handleref hndref, 
stringbuilder buffer, 
int numberofbytestoread, 
out int numberofbytesread, 
ref overlapped flag ); 
...... 
...... 
filestream fs 
= new filestream( "handleref.txt", filemode.open ); 
handleref hr 
= new handleref( fs, fs.handle ); 
stringbuilder buffer 
= new stringbuilder( 5 ); 
int read = 0
// platform invoke will hold reference to handleref until call ends 
readfile( hr, buffer, 5out read, 0 ); 

我做的关于VS.NET(C#)下获得操作系统professional  or  home的主要代码如下:

 

//作者:wudi_1982,转载请著名出处

using System.Runtime.InteropServices;

上述结构在C#中定义如下:
[ StructLayout( LayoutKind.Sequential )]   
public class OSVersionInfo 
{
public int OSVersionInfoSize;
public int majorVersion; 
public int minorVersion;
public int buildNumber;
public int platformId;

[ MarshalAs( UnmanagedType.ByValTStr, SizeConst
=128 )]    
public String versionString;
public Int16  wServicePackMajor;  
public Int16  wServicePackMinor;  
public Int16  wSuiteMask;  
public Byte  wProductType;  
public Byte  wReserved;
}



public class GetSysApi
{
   [ DllImport( 
"Kernel32.dll" )]
   
public static extern bool GetVersionEx( [In, Out] OSVersionInfo osvi );
}


private void button2_Click(object sender, System.EventArgs e)
{
   OSVersionInfo osvi 
= new OSVersionInfo();
   osvi.OSVersionInfoSize 
= Marshal.SizeOf( osvi );
  GetSysApi.GetVersionEx(osvi);
  
string tm = osvi.buildNumber+osvi.majorVersion+osvi.minorVersion+
      osvi.platformId 
+osvi.versionString+osvi.wProductType+
      osvi.wReserved
+osvi.wSuiteMask;
   MessageBox.Show(tm);
//根据那些成员变量,有足够的信息够你对操作系统进行判断
  
//我这里只写了关于windows xp professional或者windows xp home的判断
  if ( osvi.wProductType == 1)
  
{
    
if( osvi.majorVersion == 4 )
     MessageBox.Show( 
"Workstation 4.0 ");
    
else if(( osvi.wSuiteMask & 512 )!=0
      MessageBox.Show(
"Win Xp Home Edition " );
    
else MessageBox.Show("Win Xp Professional " );
   }


}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值