Calling Unmanaged DLL Functions

The .NET Framework class library has classes that provide access to most of the Windows system functions that your applications will need. In previous versions of Visual Basic, the only way to get to some of that functionality was to make calls, known as API calls, directly to the Windows system DLLs. If you find a function that isn’t handled by the Framework classes or if you would like to continue calling a Win32 API function the same way that you did in Visual Basic 6, you can use the CLR’s Platform Invoke (often shorted to PInvoke) capability to do so. Listing 2.4 shows an example of calling the PlaySound function in the Windows Multimedia DLL, winmm.dll.

In order to call functions in an unmanaged DLL, first add an Imports statement to your module that references the System.Runtime.InteropServices namespace. Rather than putting the declaration for the API function in the general declarations section of a module (the way you probably did in Visual Basic 6), in Visual Basic .NET you should create a separate class, which will wrap the function call. Each class can contain one or more function declarations. If you are using several related functions, it would make sense to make them members of the same class. All the functions declared inside the class are considered methods of the class. To call the functions from your application, create a new instance of the class and then use the familiar object.method syntax, passing any required arguments to the function. Look at the code in the btnPlaySound.Click event procedure in Listing 2.4 for an example.

Listing 2.4: Calling a Function in an Unmanaged DLL

start example
Imports System.Runtime.InteropServices Public Class Form1     Inherits System.Windows.Forms.Form Private Sub btnPlaySound_Click(ByVal sender _     As System.Object, ByVal e As System.EventArgs) _     Handles btnPlaySound.Click     Dim myWin32Object As New Win32PlaySound()     myWin32Object.PlaySound( _         "C:\WINNT\Media\The Microsoft Sound.wav", 0)     End Sub End Class Public Class Win32PlaySound     Public Declare Function PlaySound Lib "winmm.dll" _         Alias "sndPlaySoundA" (ByVal lpszSoundName As _         String, ByVal uFlags As Long) As Long End Class
end example



MCAD/MCSD(c) Visual Basic. NET XML Web Services and Server Components Study Guide
MCAD/MCSD: Visual Basic .NET XML Web Services and Server Components Study Guide
ISBN: 0782141935
EAN: 2147483647
Year: 2005
Pages: 153

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net