共用方式為


Walkthrough: Calling Windows APIs (Visual Basic)

Windows APIs are dynamic-link libraries (DLLs) that are part of the Windows operating system. You use them to perform tasks when it is difficult to write equivalent procedures of your own. For example, Windows provides a function named FlashWindowEx that lets you make the title bar for an application alternate between light and dark shades.

The advantage of using Windows APIs in your code is that they can save development time because they contain dozens of useful functions that are already written and waiting to be used. The disadvantage is that Windows APIs can be difficult to work with and unforgiving when things go wrong.

Windows APIs represent a special category of interoperability. Windows APIs do not use managed code, do not have built-in type libraries, and use data types that are different than those used with Visual Studio. Because of these differences, and because Windows APIs are not COM objects, interoperability with Windows APIs and the .NET Framework is performed using platform invoke, or PInvoke. Platform invoke is a service that enables managed code to call unmanaged functions implemented in DLLs. For more information, see Consuming Unmanaged DLL Functions. You can use PInvoke in Visual Basic by using either the Declare statement or applying the DllImport attribute to an empty procedure.

Windows API calls were an important part of Visual Basic programming in the past, but are seldom necessary with Visual Basic 2005. Whenever possible, you should use managed code from the .NET Framework to perform tasks, instead of Windows API calls. This walkthrough provides information for those situations in which using Windows APIs is necessary.

Note

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Customizing Development Settings.

API Calls Using Declare

The most common way to call Windows APIs is by using the Declare statement.

To declare a DLL procedure

  1. Determine the name of the function you want to call, plus its arguments, argument types, and return value, as well as the name and location of the DLL that contains it.

    Note

    For complete information about the Windows APIs, see the Win32 SDK documentation in the Platform SDK Windows API. For more information about the constants that Windows APIs use, examine the header files such as Windows.h included with the Platform SDK.

  2. Open a new Windows Application project by clicking New on the File menu, and then clicking Project. The New Project dialog box appears.

  3. Select Windows Application from the list of Visual Basic project templates. The new project is displayed.

  4. Add the following Declare function either to the class or module in which you want to use the DLL:

    Declare Auto Function MBox Lib "user32.dll" Alias "MessageBox" (
        ByVal hWnd As Integer,
        ByVal txt As String,
        ByVal caption As String,
        ByVal Typ As Integer) As Integer
    

Parts of the Declare Statement

The Declare statement includes the following elements.

Auto modifier

The Auto modifier instructs the runtime to convert the string based on the method name according to common language runtime rules (or alias name if specified).

Lib and Alias keywords

The name following the Function keyword is the name your program uses to access the imported function. It can be the same as the real name of the function you are calling, or you can use any valid procedure name and then employ the Alias keyword to specify the real name of the function you are calling.

Specify the Lib keyword, followed by the name and location of the DLL that contains the function you are calling. You do not need to specify the path for files located in the Windows system directories.

Use the Alias keyword if the name of the function you are calling is not a valid Visual Basic procedure name, or conflicts with the name of other items in your application. Alias indicates the true name of the function being called.

Argument and Data Type Declarations

Declare the arguments and their data types. This part can be challenging because the data types that Windows uses do not correspond to Visual Studio data types. Visual Basic does a lot of the work for you by converting arguments to compatible data types, a process called marshaling. You can explicitly control how arguments are marshaled by using the MarshalAsAttribute attribute defined in the System.Runtime.InteropServices namespace.

Note

Previous versions of Visual Basic allowed you to declare parameters As Any, meaning that data of any data type could be used. Visual Basic requires that you use a specific data type for all Declare statements.

Windows API Constants

Some arguments are combinations of constants. For example, the MessageBox API shown in this walkthrough accepts an integer argument called Typ that controls how the message box is displayed. You can determine the numeric value of these constants by examining the #define statements in the file WinUser.h. The numeric values are generally shown in hexadecimal, so you may want to use a calculator to add them and convert to decimal. For example, if you want to combine the constants for the exclamation style MB_ICONEXCLAMATION 0x00000030 and the Yes/No style MB_YESNO 0x00000004, you can add the numbers and get a result of 0x00000034, or 52 decimal. Although you can use the decimal result directly, it is better to declare these values as constants in your application and combine them using the Or operator.

To declare constants for Windows API calls

  1. Consult the documentation for the Windows function you are calling. Determine the name of the constants it uses and the name of the .h file that contains the numeric values for these constants.

  2. Use a text editor, such as Notepad, to view the contents of the header (.h) file, and find the values associated with the constants you are using. For example, the MessageBox API uses the constant MB_ICONQUESTION to show a question mark in the message box. The definition for MB_ICONQUESTION is in WinUser.h and appears as follows:

    #define MB_ICONQUESTION 0x00000020L

  3. Add equivalent Const statements to your class or module to make these constants available to your application. For example:

    Const MB_ICONQUESTION As Integer = &H20
    Const MB_YESNO As Integer = &H4
    Const IDYES As Integer = 6
    Const IDNO As Integer = 7
    

To call the DLL procedure

  1. Add a button named Button1 to the startup form for your project, and then double-click it to view its code. The event handler for the button is displayed.

  2. Add code to the Click event handler for the button you added, to call the procedure and provide the appropriate arguments:

    Private Sub Button1_Click(ByVal sender As System.Object,
        ByVal e As System.EventArgs) Handles Button1.Click
    
        ' Stores the return value. 
        Dim RetVal As Integer
        RetVal = MBox(0, "Declare DLL Test", "Windows API MessageBox",
            MB_ICONQUESTION Or MB_YESNO)
    
        ' Check the return value. 
        If RetVal = IDYES Then
            MsgBox("You chose Yes")
        Else
            MsgBox("You chose No")
        End If 
    End Sub
    
  3. Run the project by pressing F5. The message box is displayed with both Yes and No response buttons. Click either one.

Data Marshaling

Visual Basic automatically converts the data types of parameters and return values for Windows API calls, but you can use the MarshalAs attribute to explicitly specify unmanaged data types that an API expects. For more information about interop marshaling, see Interop Marshaling.

To use Declare and MarshalAs in an API call

  1. Determine the name of the function you want to call, plus its arguments, data types, and return value.

  2. To simplify access to the MarshalAs attribute, add an Imports statement to the top of the code for the class or module, as in the following example:

    Imports System.Runtime.InteropServices
    
  3. Add a function prototype for the imported function to the class or module you are using, and apply the MarshalAs attribute to the parameters or return value. In the following example, an API call that expects the type void* is marshaled as AsAny:

    Declare Sub SetData Lib "..\LIB\UnmgdLib.dll" (
        ByVal x As Short,
        <MarshalAsAttribute(UnmanagedType.AsAny)>
            ByVal o As Object)
    

API Calls Using DllImport

The DllImport attribute provides a second way to call functions in DLLs without type libraries. DllImport is roughly equivalent to using a Declare statement but provides more control over how functions are called.

You can use DllImport with most Windows API calls as long as the call refers to a shared (sometimes called static) method. You cannot use methods that require an instance of a class. Unlike Declare statements, DllImport calls cannot use the MarshalAs attribute.

To call a Windows API using the DllImport attribute

  1. Open a new Windows Application project by clicking New on the File menu, and then clicking Project. The New Project dialog box appears.

  2. Select Windows Application from the list of Visual Basic project templates. The new project is displayed.

  3. Add a button named Button2 to the startup form.

  4. Double-click Button2 to open the code view for the form.

  5. To simplify access to DllImport, add an Imports statement to the top of the code for the startup form class:

    Imports System.Runtime.InteropServices
    
  6. Declare an empty function preceding the End Class statement for the form, and name the function MoveFile.

  7. Apply the Public and Shared modifiers to the function declaration and set parameters for MoveFile based on the arguments the Windows API function uses:

    Public Shared Function MoveFile(
        ByVal src As String,
        ByVal dst As String) As Boolean 
        ' Leave the body of the function empty. 
    End Function
    

    Your function can have any valid procedure name; the DllImport attribute specifies the name in the DLL. It also handles interoperability marshaling for the parameters and return values, so you can choose Visual Studio data types that are similar to the data types the API uses.

  8. Apply the DllImport attribute to the empty function. The first parameter is the name and location of the DLL containing the function you are calling. You do not need to specify the path for files located in the Windows system directories. The second parameter is a named argument that specifies the name of the function in the Windows API. In this example, the DllImport attribute forces calls to MoveFile to be forwarded to MoveFileW in KERNEL32.DLL. The MoveFileW method copies a file from the path src to the path dst.

    <DllImport("KERNEL32.DLL", EntryPoint:="MoveFileW", SetLastError:=True,
        CharSet:=CharSet.Unicode, ExactSpelling:=True,
        CallingConvention:=CallingConvention.StdCall)>
    Public Shared Function MoveFile(
        ByVal src As String,
        ByVal dst As String) As Boolean 
        ' Leave the body of the function empty. 
    End Function
    
  9. Add code to the Button2_Click event handler to call the function:

    Private Sub Button2_Click(ByVal sender As System.Object,
        ByVal e As System.EventArgs) Handles Button2.Click
    
        Dim RetVal As Boolean = MoveFile("c:\tmp\Test.txt", "c:\Test.txt")
        If RetVal = True Then
            MsgBox("The file was moved successfully.")
        Else
            MsgBox("The file could not be moved.")
        End If 
    End Sub
    
  10. Create a file named Test.txt and place it in the C:\Tmp directory on your hard drive. Create the Tmp directory if necessary.

  11. Press F5 to start the application. The main form appears.

  12. Click Button2. The message "The file was moved successfully" is displayed if the file can be moved.

See Also

Reference

Declare Statement

DllImportAttribute

MarshalAsAttribute

Auto (Visual Basic)

Alias Clause (Visual Basic)

Concepts

Creating Prototypes in Managed Code

Callback Sample

Other Resources

COM Interop (Visual Basic)