Compartilhar via


Passo a passo: Chamando APIs do Windows (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 Consumir funções DLL não gerenciada. You can use PInvoke in Visual Basic by using either the Declare statement or applying the DllImport attribute to an empty procedure.

Chamadas de API do Windows foram uma parte importante da Visual Basic de programação no passado, mas são raramente necessário com o 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.

ObservaçãoObservação

Seu computador pode mostrar nomes ou locais diferentes para alguns dos elementos da interface do usuário do Visual Studio nas instruções a seguir. A edição do Visual Studio que você possui e as configurações que você usa determinam esses elementos. Para obter mais informações, consulte Configurações do Visual Studio.

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.

    ObservaçãoObservação

    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 o Aliaspalavra-chave se o nome de função que você está chamando é não válido Visual Basicnome doprocedimento ou conflita com o nome de outros itens em seu aplicativo. Aliasindica o verdadeiro nome da função que está sendo chamado.

Argument and Data Type Declarations

Declare the arguments and their data types. Esta parte pode ser desafiador porque os tipos de dados que usa o Windows não correspondem aos tipos de dados de Visual Studio . Visual Basicfaz uma grande parte do trabalho para você convertendo os argumentos para os tipos de dados compatíveis, um processo chamado marshaling. You can explicitly control how arguments are marshaled by using the MarshalAsAttribute attribute defined in the System.Runtime.InteropServices namespace.

ObservaçãoObservação

VersõesAnterior de Visual Basic permitia que você declarar parâmetros As Any, que significa que os dados de qualquer tipo de dados pode ser usado. Visual Basicexige que você use um específico tipo de dados para todas as Declare instruções.

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. Você pode determinar o valor numérico das constantes examinando o #define instruções no arquivo WINUSER. H. Os valores numéricos geralmente são mostrados em hexadecimal, você poderá usar uma calculadora para adicioná-los e converter em 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. Para obter mais informações sobre o marshaling de interoperabilidade, consulte 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

O DllImport atributo fornece uma segunda maneira de chamar funções em DLLs sem bibliotecas de tipos. DllImporté basicamente equivalente ao uso de um Declarededemonstrativo mas oferece mais controle sobre como as funções são chamadas.

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. Neste exemplo, o DllImport atributo força chamadas para MoveFile para ser encaminhada ao MoveFileW em 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.

Consulte também

Referência

Instrução Declare

DllImportAttribute

MarshalAsAttribute

Auto (Visual Basic)

Cláusula Alias (Visual Basic)

Conceitos

A criação de protótipos em código gerenciado

Exemplo de retorno de chamada

Outros recursos

Interoperabilidade COM (Visual Basic)