In addition to COM and COM+ components , the .NET Framework can access other types of unmanaged code libraries. .NET can call functions from unmanaged Windows API libraries through the use of Platform Invoke (PInvoke), as described in the following steps: -
After creating a new Windows application, add a new module named API.vb . -
Add the following code to the API.vb module: Public Module API Declare Auto Function GetComputerName Lib "kernel32" ( _ ByVal lpBuffer As String, ByRef nSize As Integer) As Integer End Module -
After creating a new form within your project, add the following code at the top of the form's code module: Imports System.Text -
You may now use the API's functionality, such as in the following code example, which displays the computer's name in the lblComputerName Label control: Private Sub SampleForm_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Dim buf As String = New String(CChar(" "), 128) Dim len As Integer = buf.Length Dim ret As Integer ret = GetComputerName(buf, len) lblComputerName.Text = "This computer is named " & _ buf.ToString.SubString(1, len) End Sub The code in Step 2 demonstrates the PInvoke facility. The Declare statement specifies the name of the API call ( GetComputerName ), the name of the library that contains the call ( kernel32 ), and the parameters to the API call ( lpBuffer and nSize ). | PInvoke is also able to use API calls that require structures as parameters. This is important because many Windows API calls require you to pass a structure containing additional information. | As you've seen in this chapter, you have a variety of ways to call non-.NET code from your .NET applications. When you're working with .NET, your long- term goal should be to translate your entire application into native .NET code. Particularly when you're upgrading an existing application, though, it can be very useful to call legacy components from your new code. |