Call+Win32+API+from+Managed+Code

Sometimes you may have a need for a function for which there is no managed type. Even though this is rare to find today, however, there are cases where a managed equivalent does not exist. You may also need to call a third party API (for example Essbase API) from within .NET code. To do this, here is a code sample

code format="vbnet" Imports System.Runtime.InteropServices

Partial Class _Default Inherits System.Web.UI.Page

Public Structure OSVersionInfo Public OSVersionInfoSize As Integer Public majorVersion As Integer Public minorVersion As Integer Public buildNumber As Integer Public platformId As Integer  _ Public versionString As String End Structure

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles Button1.Click Dim osvi As New OSVersionInfo osvi.OSVersionInfoSize = Marshal.SizeOf(osvi)

If GetVersionEx(osvi) Then Dim result As String = String.Format("Windows Version: {0}.{1}.{2}.{3}",               osvi.majorVersion, osvi.minorVersion,                osvi.buildNumber, osvi.platformId) Response.Write(result) End If   End Sub

Declare Ansi Function GetVersionEx Lib "kernel32.dll" _ Alias "GetVersionExA" (ByRef osvi As OSVersionInfo) As Boolean

End Class

''in aspx page have button with id button1

code
 * We have declared the function using Declare. To get a list of all functions, go here.
 * We have defined a structure because the API expects a structure to populate its results
 * When declaring constants, make sure you declare them correctly in hexadecimal format. Click here to read more about this topic.

To learn more about this topic, here are some useful links:

http://msdn.microsoft.com/en-us/library/172wfck9%28VS.71%29.aspx