To declare the
GetVersionEx function, you can pretty much follow the same
DllImport pattern as you saw in
first part of this article. One new twist is that the code applies both
In and
Out direction attributes to the
OSVersionInfo parameter, so that the managed caller can see the changes the unmanaged code makes to the structure. A
ref attribute would also have worked.
[ DllImport( "kernel32" )]
public static extern bool GetVersionEx(
[In, Out] OSVersionInfo osvi );
You can now instantiate the
OSVersionInfo class just like any other class. The
Marshal.SizeOf() method determines the size of the unmanaged structure, in bytes, which is what the API function need to know.
[STAThread]
static void Main(string[] args)
{
OSVersionInfo osvi = new OSVersionInfo();
osvi.dwOSVersionInfoSize =
Marshal.SizeOf( osvi );
GetVersionEx( osvi );
Printing out the results of the call is now a trivial exercise:
Console.WriteLine( "GetVersionEx results");
Console.WriteLine( "Class size: {0}",
osvi.dwOSVersionInfoSize );
Console.WriteLine( "Major Version: {0}",
osvi.dwMajorVersion );
Console.WriteLine( "Minor Version: {0}",
osvi.dwMinorVersion );
Console.WriteLine( "Build Number: {0}",
osvi.dwBuildNumber );
Console.WriteLine( "Platform Id: {0}",
osvi.dwPlatformId );
Console.WriteLine( "CSD Version: {0}",
osvi.szCSDVersion );
For most purposes, you won't need to go through all of that to find out what OS platform and version is running: the
Environment.OSVersion class contains the Platform Id and the version/build string, although not the CSD version string (which indicates the service pack level).
Console.WriteLine(
"\nEnvironment.OSVersion results");
Console.WriteLine( "Platform: {0}",
Environment.OSVersion.Platform );
Console.WriteLine( "Version: {0}",
Environment.OSVersion.Version );
}
}
}
On my Windows 2000 machine, this code produces the following output:
GetVersionEx results
Class size: 148
Major Version: 5
Minor Version: 0
Build Number: 2195
Platform Id: 2
CSD Version: Service Pack 2
Environment.OSVersion results
Platform: Win32NT
Version: 5.0.2195.0
For a good idea of how to accomplish the same thing in VB.NET, you should consult the .NET
OSInfo sample, which was my starting point for the fleshed-out sample above.