funções na API do Windows

funções na API do Windows


MAIS INFORMAÇÕES


Although Visual Basic has an extensive list of statements, methods, events, and procedures to help you create a Windows program quickly and easily, there are limitations within the development environment that may prevent you from implementing your ideas. Embora o Visual Basic tem uma extensa lista de indicações, métodos, eventos e procedimentos que ajudam a criar um programa de Windows com rapidez e facilidade, há limitações no ambiente de desenvolvimento que pode impedir a execução suas idéias. One way to go beyond these limitations is to call the Windows API from within your Visual Basic project. Uma forma de ultrapassar estas limitações é chamar a API do Windows de dentro do seu projeto Visual Basic. At the heart of the Windows operating system are the functions that make up the Windows API. No coração do sistema operacional Windows são as funções que compõem a API do Windows. The majority of these functions are accessible from Visual Basic programs. A maioria dessas funções são acessíveis a partir de Visual Basic de programas.

The following topics are covered in this article: Os seguintes tópicos são abordados neste artigo:

  • What is the Windows API? Qual é a API do Windows? - A brief overview of the Windows Application Programming Interface. - Uma breve descrição do aplicativo Windows Programming Interface.

  • Why Use the Windows API? Por que usar a API do Windows? - Explains the advantages of calling Windows API functions in addition to using the functions, methods, and procedures provided by Visual Basic. - Explica as vantagens de chamar funções de API do Windows, além de usar as funções, métodos e procedimentos fornecidos pelo Visual Basic.

  • How to call a Windows API function - The details of calling a function from a Visual Basic program. Como chamar um função API do Windows - Os detalhes da chamada de uma função a partir de um programa Visual Basic.

  • Sample Project - Shows how to create your first Visual Basic project that calls two functions in the Windows API. Exemplo de Projeto - Mostra como criar seu primeiro projeto do Visual Basic que chama duas funções na API do Windows.

  • Tips - Some tips and tricks to make Windows API programming easier. Dicas - Alguns truques e dicas para tornar o Windows API de programação mais fácil.

  • Where to go from here? Para onde ir a partir daqui? - additional resources and articles on the topics of using the Windows API with Visual Basic. - Recursos adicionais e artigos sobre os temas de usar a API do Windows com o Visual Basic.


Back to the top Voltar ao topo

What is the Windows API? Qual é a API do Windows?


If you look at the Windows System directory, typically \Windows\System under Window 95/98 and \Winnt\System32 under Windows NT, you will find a number of Dynamic Link Library (.DLL) files. Se você olhar o diretório de sistema do Windows, normalmente \ Windows \ System no Windows 95/98 e Winnt \ System32 no Windows NT, você encontrará uma série de (Dynamic Link Library. DLL). These files contain functions that are used to run the operating system and to ensure a consistent user interface and operating environment. Esses arquivos contêm funções que são usadas para executar o sistema operacional e assegurar a interface de usuário consistente e ambiente operacional. These files make up the Windows API. Estes arquivos formam a API do Windows.

The purpose of the Windows API is to allow you to develop programs consistent with the Windows operating system and user interface. O objetivo da API do Windows é permitir que você a desenvolver programas compatíveis com o sistema operacional Windows e interface do usuário. Instead of individuals writing the code to create components of the Windows operating system, such as forms, command buttons, and menus, you can call the appropriate functions in the Windows API and let the operating system create those components. Ao invés de indivíduos escrever o código para criar componentes do sistema operacional Windows, tais como formulários, botões de comando e menus, você pode chamar as funções apropriadas na API do Windows e deixar o sistema operacional criar esses componentes.

The purpose of each function in the Windows API is documented in the Platform Software Development Kit (SDK). A finalidade de cada função na API do Windows é documentada no Platform Software Development Kit (SDK). The Platform SDK is shipped with Microsoft Visual C++ and as part of a subscription to the Microsoft Developer Network (MSDN.) A Plataforma SDK é fornecido com o Microsoft Visual C + + e como parte de uma assinatura do Microsoft Developer Network (MSDN.)

You can also download the Platform SDK from the following Microsoft Web site: Você também pode baixar o Platform SDK a partir do seguinte site da Microsoft:

http://www.microsoft.com/msdownload/platformsdk/setuplauncher.htm (http://www.microsoft.com/msdownload/platformsdk/setuplauncher.htm) http://www.microsoft.com/msdownload/platformsdk/setuplauncher.htm http://www.microsoft.com/msdownload/platformsdk/setuplauncher.htm ()

As with any other Windows program, Visual Basic uses the functions in the Windows API. Tal como acontece com qualquer outro programa Windows, Visual Basic usa as funções da API do Windows. When you perform a task in Visual Basic, such as adding a command button to a form, Visual Basic calls the appropriate functions to perform the task. Quando você executa uma tarefa no Visual Basic, como adicionar um botão de comando a um formulário, o Visual Basic chama as funções necessárias para executar a tarefa. The features of Visual Basic are wrappers to these functions. As características do Visual Basic são invólucros para essas funções.

Back to the top Voltar ao topo

Why Use the Windows API? Por que usar a API do Windows?


The reason why you would use the Windows API is to perform a task beyond what is available from Visual Basic. A razão porque você usaria o Windows API é realizar uma tarefa além do que está disponível no Visual Basic. For example, you cannot determine or set the cursor blinking rate through any statement, property, procedure, or method in Visual Basic. Por exemplo, você não pode determinar ou definir o cursor piscando taxa através de qualquer declaração, propriedade, procedimento ou método no Visual Basic. You can get the blink rate by calling the GetCaretBlinkTime function, which returns the cursor blink rate in milliseconds. Você pode obter a taxa de intermitência chamando a função GetCaretBlinkTime, que retorna a taxa de intermitência do cursor em milisegundos. If you want to set the cursor to blink at another rate under specified conditions, you can call the SetCaretBlinkTime function, passing the specified time in milliseconds. Se você quiser colocar o cursor a piscar em outro ritmo, em condições definidas, você pode chamar a função SetCaretBlinkTime, passando o tempo especificado em milissegundos.

You can get the same functionality as almost any of the features of Visual Basic by calling the appropriate Windows API functions. Você pode obter a mesma funcionalidade que quase todos os recursos do Visual Basic chamando a API apropriada funções do Windows. However, calling these functions directly is typically more complicated and can cause unpredictable behavior if not done correctly, resulting in system errors. For the best performance and predictable behavior, you should use the intrinsic Visual Basic functionality. No entanto, chamar essas funções diretamente normalmente é mais complicado e pode causar um comportamento imprevisível se não for feito corretamente, resultando em erros do sistema. Para o melhor desempenho e comportamento previsível, você deve usar a funcionalidade intrínseca Visual Basic.

Back to the top Voltar ao topo

How to Call a Windows API Function Como chamar uma função API do Windows


There are two steps required to call a Windows API function: Há duas etapas necessárias para chamar uma função API do Windows:

  • Declare the function in a module or form. Declare a função em um módulo ou formulário.

  • Call the function in your program as you would any other function. Chame a função no seu programa como se fosse qualquer outra função.


The topic "Declaring a DLL Procedure" in "Part 4 Accessing DLLs and the Windows API" of the "Visual Basic Component Tools Guide" explains how to declare a function in a module. O tópico "Declarar um procedimento DLL" em "Parte 4 Acessando e DLLs API do Windows", do "Visual Basic componente Ferramentas Guide" explica como declarar uma função em um módulo. The topic also shows how to use the API Text Viewer to find the appropriate declaration and copy and paste the declaration to your project. O tópico também mostra como usar a API Text Viewer para encontrar a declaração adequada e copiar e colar a declaração de seu projeto.

For example, to declare the GetCaretBlinkTime function in a module, copy the following text to the code window of your module: Por exemplo, para declarar a função GetCaretBlinkTime em um módulo, copie o seguinte texto para a janela de código do módulo:

Declare Function GetCaretBlinkTime Lib "user32" Alias _ Declare Function GetCaretBlinkTime Lib "user32" Alias _                 "GetCaretBlinkTime" () As Long "GetCaretBlinkTime" () As Long

If you want to use the same function only in a specific form, add the keyword "Private" to the beginning of the function declaration. Se você quiser usar a mesma função apenas em um formulário específico, adicione a palavra "privado" para o início da declaração da função. The GetCaretBlinkTime function declaration is written in the code window of a form as follows: A declaração da função GetCaretBlinkTime está escrito na janela de código de uma forma como se segue:

Private Declare Function GetCaretBlinkTime Lib "user32" Alias _ Private Declare Function GetCaretBlinkTime Lib "user32" Alias _                         "GetCaretBlinkTime" () As Long "GetCaretBlinkTime" () As Long

This function returns a Long value that is the cursor blink rate in milliseconds. Esta função retorna um valor Long que é a taxa de intermitência do cursor em milisegundos. The Lib keyword precedes the name of the file that contains the function; in this case, User32.DLL. A palavra-chave Lib precede o nome do arquivo que contém a função, neste caso, user32.dll. The Alias keyword is used to define the specific function in the DLL file. Alias a palavra-chave é usado para definir a função específica no arquivo DLL. This clause is optional when the function is being declared with the same name as in the DLL. Esta cláusula é opcional quando a função está sendo declarada com o mesmo nome na DLL.

You will often see the Private notation used in Microsoft Knowledge Base articles because not using a module streamlines the implementation of the sample code. Você vai ver muitas vezes a notação privados utilizados na Microsoft Knowledge Base artigos, porque não usar um módulo simplifica a implementação do código de exemplo. If you need to use a Windows API function in more than one source file in a project, it should be declared in a module. Se você precisa usar uma função API do Windows em que um arquivo de origem mais um projeto, ele deve ser declarado em um módulo.

For more information about the Declare statement, see "Declare Statement" in the Language Reference in Books Online. Para obter mais informações sobre a declaração Declare, consulte "Declare declaração" na Referência da Linguagem no Books Online.

Once you have declared the function, you can call it as you would any Visual Basic function and a pass any appropriate parameters. Depois de ter declarado a função, você pode chamá-lo como você teria qualquer função do Visual Basic e passar os parâmetros adequados. The following example shows how to call the GetCaretBlinkTime function: O exemplo a seguir mostra como chamar a função GetCaretBlinkTime:

Dim lngCaretBlinkTime as Long   ' Blink Rate variable Dim lngCaretBlinkTime como variável Long 'Taxa de Intermitência   lngCaretBlinkTime =  GetCaretBlinkTime lngCaretBlinkTime = GetCaretBlinkTime

For functions that require parameters, you can pass parameters by reference or by value. Para funções que exigem parâmetros, você pode passar parâmetros por referência ou por valor.

A parameter passed by reference passes the 32-bit address of the location where the value is stored. Um parâmetro passado por referência passa o endereço de 32 bits do local onde o valor é armazenado. By default, Visual Basic passes parameters by reference. Por padrão, o Visual Basic passa parâmetros por referência. You can also explicitly pass parameters by reference using the ByRef keyword. Você também pode explicitamente passar parâmetros por referência usando a palavra-chave ByRef.

The values of parameters passed by reference can be changed in the called procedure. Os valores dos parâmetros passados por referência pode ser alterado no procedimento chamado. For example, the InvertRect function inverts a specified rectangle by inverting the value of each pixel. Por exemplo, a função InvertRect inverte um retângulo especificado por invertendo o valor de cada pixel. The function requires the handle to the device context containing the rectangle and the address of a user defined type (UDT) variable with the logical coordinates of the rectangle. A função requer o identificador para o contexto dispositivo que contém o retângulo eo endereço de um tipo definido pelo usuário (UDT), variável com a lógica coordenadas do retângulo. The address of the user defined variable is passed by reference. O endereço da variável definida pelo usuário é passado por referência.

When you call this function, the logical coordinates of the rectangle are placed in the user defined variable. Quando você chamar essa função, a lógica coordenadas do retângulo são colocados na variável definida pelo usuário.

To use this function, add the following declarations to a module: Para usar essa função, adicione as seguintes declarações a um módulo:

Public Type RECT Tipo Pública RECT      Left As Long Esquerda As Long      Top As Long Top As Long      Right As Long Right As Long      Bottom As Long No fundo Long   End Type End Type    Declare Function InvertRect Lib "user32" Alias "InvertRect" _ Declarar Função InvertRect Lib "user32" Alias "InvertRect" _   (ByVal hdc As Long, ByRef lpRect As RECT) As Long (ByVal hdc As Long, ByRef lpRect Como RECT) As Long

The first declaration specifies a user defined type required for a parameter of the InvertRect function while the second declaration is for the function. A primeira declaração especifica um tipo definido pelo usuário necessários para um parâmetro da função InvertRect enquanto a segunda declaração é para a função.

Passing a parameter by value sends the actual value of the parameter to the function. Passar um parâmetro por valor envia o valor real do parâmetro para a função. You pass a parameter by value if the parameter is not changed by the called procedure. Você passa um parâmetro por valor se o parâmetro não é alterado pelo procedimento chamado. To pass a parameter by value, add the ByVal keyword to each parameter you want to pass to the function. Para passar um parâmetro por valor, adicione a palavra-chave ByVal para cada parâmetro que deseja passar para a função.

NOTE: When you pass a string variable to an API call, you actually pass the memory address of the string, so you should always pass string parameters as ByVal. NOTA: Quando você passar uma variável string para uma chamada de API, você realmente passar o endereço de memória da string, então você deve sempre passar parâmetros seqüência de caracteres como ByVal. If you pass a string parameter by reference, you pass the memory address containing the memory address of the string, which causes the API function receiving the parameter to behave incorrectly and may cause a memory violation error. Se você passar um parâmetro de cadeia por referência, você passa o endereço de memória contendo o endereço de memória da seqüência de caracteres, o que faz com que a função da API receber o parâmetro para se comportar de forma incorrecta e pode causar um erro de violação de memória.

The SetCaretBlinkTime function requires the rate in milliseconds parameter to be passed by value to the function. A função exige SetCaretBlinkTime a taxa em milissegundos parâmetro a ser passado por valor para a função. Declare this function by adding the following statement to a module: Declare esta função, adicionando a seguinte declaração para um módulo:

Declare Function SetCaretBlinkTime Lib "user32" Alias _ Declare Function SetCaretBlinkTime Lib "user32" Alias _   "SetCaretBlinkTime" (ByVal wMSeconds As Long) As Long "SetCaretBlinkTime" (ByVal wMSeconds As Long) As Long

To use this function to set the cursor blink rate to 250 milliseconds, add the following to your project: Para usar essa função para definir a taxa de intermitência do cursor para 250 milissegundos, adicione o seguinte ao seu projeto:

Dim lBlinkRate as Long   ' Blink rate variable Dim lBlinkRate como a taxa de Long 'Blink variávelDim lResult as Long      ' Result Variable Dim lResultado como resultado variável Long 'lBlinkRate = 250 lBlinkRate = 250lResult = SetCaretBlinkTime (lBlinkRate) lResultado = SetCaretBlinkTime (lBlinkRate)If lResult = 0 Then Se lResultado = 0 Then   ' Error code "Código de erroEnd If End If

Back to the top Voltar ao topo

Sample Project Exemplo de projeto


This section shows you how to create a sample project that controls the cursor blink rate by calling two functions in the Windows API. Esta seção mostra como criar um projeto exemplo que controla a taxa de intermitência do cursor chamando duas funções na API do Windows. The GetCaretBlinkRate function returns the current blink rate in milliseconds while the SetCaretBlinkRate function sets the blink rate. A função GetCaretBlinkRate retorna a taxa de intermitência atual em milissegundos, enquanto a função SetCaretBlinkRate define a taxa de intermitência. Both of these functions will be declared in a module. Ambas estas funções serão declaradas em um módulo. You can also declare these functions in the form by prefacing each function declaration with the Private keyword. Você pode também declarar essas funções na forma por prefaciar cada declaração de função com a palavra-chave Private.

NOTE: The SetCaretBlinkRate function sets the cursor blink rate for the operating system. NOTA: A função SetCaretBlinkRate define a taxa de intermitência do cursor para o sistema operacional. If you exit the project before setting the blink rate back to the default, the cursor blink rate will change for all programs. Se você sair do projeto antes de definir a taxa de intermitência de volta para o padrão, a taxa de intermitência do cursor vai mudar para todos os programas.

Back to the top Voltar ao topo

Step-by-Step Example Passo-a-Passo Exemplo



  1. Start a new Standard EXE project in Visual Basic. Iniciar um novo projeto Standard EXE no Visual Basic. Form1 is created by default. Form1 é criado por padrão.

  2. Add a Module to the project by completing the following steps: Adicionar um módulo ao projeto, concluindo os seguintes passos:




    1. From the Project menu, click Add module. A partir do menu Project, clique em Adicionar módulo. The Add Module dialog box appears. O Add Module caixa de diálogo aparece.

    2. From the New tab, choose Module and click OK. A partir do novo guia, escolha o módulo e clique em OK. A new module, Module1, is added to your project. Um novo módulo Módulo1, é adicionado ao seu projeto.


  1. Copy the following code to the Code window of Module1: Copie o seguinte código para a janela de código Módulo1:


4.  Option Explicit Option Explicit5.   6.  ' Returns the current cursor blink rate "Retorna a taxa de intermitência do cursor atual7.  Declare Function GetCaretBlinkTime Lib "user32" () As Long Declare Function GetCaretBlinkTime Lib "user32" () As Long8.   9.  ' Sets the cursor blink rate 'Define a taxa de intermitência do cursor10.Declare Function SetCaretBlinkTime Lib "user32" _ Declare Function SetCaretBlinkTime Lib "user32" _11.                (ByVal wMSeconds As Long) As Long (WMSeconds ByVal As Long) As Long12. 13.' Returns the error code if either GetCaretBlinkTime or "Retorna o código de erro se quer ou GetCaretBlinkTime14.' SetCaretBlinkTime functions fails «Funções SetCaretBlinkTime falhar15.Public Declare Function GetLastError Lib "kernel32" () As Long Public Declare Function GetLastError Lib "kernel32" () As Long

  1. Add a HScrollBar, a TextBox, and a CommandButton to Form1. Adicionar um HScrollBar, um TextBox e um CommandButton para Form1.

  2. Copy the following code to the Code window of Form1: Copie o seguinte código para a janela de código Form1:


18.Option Explicit Option Explicit19.Dim lDefaultTime As Long As Long Dim lDefaultTime20.Dim lResult As Long As Long Dim lResultado21.Dim lErrorCode As Long As Long Dim lErrorCode22. 23.Private Sub Form_Load() Private Sub Form_Load ()24.   lResult = GetCaretBlinkTime lResultado = GetCaretBlinkTime25. 26.   If lResult = 0 Then Se lResultado = 0 Then27.      Call DisplayError(0) Call DisplayError (0)28.   Else Outro29.      lDefaultTime = lResult lDefaultTime = lResultado30.      HScroll1.Min = 10 HScroll1.Min = 1031.      HScroll1.Max = 1000 HScroll1.Max = 100032.      HScroll1.Value = lDefaultTime HScroll1.Value = lDefaultTime33.      Text1.Text = CStr(lDefaultTime) Text1.Text = CStr (lDefaultTime)34.      Command1.Caption = "Return to Default" Command1.Caption = "Voltar ao padrão"35.   End If End If36.End Sub End Sub37. 38.Private Sub Command1_Click() Private Sub Command1_Click ()39.   lResult = SetCaretBlinkTime(lDefaultTime) lResultado = SetCaretBlinkTime (lDefaultTime)40.   41.   ' If the function fails then display a message box with the error code "Se a função falhar, em seguida, exibir uma caixa de mensagem com o código de erro42.   If lResult = 0 Then Se lResultado = 0 Then43.      Call DisplayError(1) Call DisplayError (1)44.   Else Outro45.      ' Display the new blink rate. "Mostrar a taxa de intermitência do novo.46.      HScroll1.Value = lDefaultTime HScroll1.Value = lDefaultTime47.      Text1.Text = CStr(GetCaretBlinkTime) Text1.Text = CStr (GetCaretBlinkTime)48.      HScroll1.SetFocus HScroll1.SetFocus49.   End If End If50.End Sub End Sub51. 52.Private Sub HScroll1_Change() HScroll1_Change Private Sub ()53.   lResult = SetCaretBlinkTime(HScroll1.Value) lResultado = SetCaretBlinkTime (HScroll1.Value)54. 55.   If lResult = 0 Then Caso lResultado = 0 Then56.      Call DisplayError(1) Call DisplayError (1)57.   Else Outro58.      lResult = GetCaretBlinkTime lResultado = GetCaretBlinkTime59.      If GetCaretBlinkTime = 0 Then Se GetCaretBlinkTime = 0 Then60.         Call DisplayError(0) Call DisplayError (0)61.      Else Outro62.         Text1.Text = CStr(lResult) Text1.Text = CStr (lResultado)63.      End If End If64.   End If End If65.End Sub End Sub66. 67.Private Sub HScroll1_Scroll() Private Sub HScroll1_Scroll ()68.   Text1.Text = CStr(HScroll1.Value) Text1.Text = CStr (HScroll1.Value)69.End Sub End Sub70. 71.Private Sub Text1_KeyPress(KeyAscii As Integer) Private Sub Text1_KeyPress (KeyAscii As Integer)72.   If KeyAscii = vbKeyReturn Then Se KeyAscii = Então vbKeyReturn73.      Dim iTextValue As Integer As Integer Dim iTextValue74.      iTextValue = CInt(Text1.Text) iTextValue = CInt (Text1.Text)75. 76.      If iTextValue > 1000 Or iTextValue < 10 Then Se iTextValue> 1000 ou iTextValue <10 então77.         MsgBox "Enter a number between 10 and 1000." MsgBox "Digite um número entre 10 e 1000".78.         Text1.Text = CStr(HScroll1.Value) Text1.Text = CStr (HScroll1.Value)79.         Exit Sub Exit Sub80.      Else Outro81.         HScroll1.Value = iTextValue HScroll1.Value = iTextValue82.      End If End If83.   End If End If84.End Sub End Sub85. 86.Private Sub Form_Terminate() Private Sub Form_Terminate ()87.   lResult = SetCaretBlinkTime(lDefaultTime) lResultado = SetCaretBlinkTime (lDefaultTime)88. 89.   If lResult = 0 Then Se lResultado = 0 Then90.      lErrorCode = GetLastError lErrorCode = GetLastError91.      MsgBox ("SetCaretBlinkTime failed. Error" & CStr(lErrorCode)) MsgBox ("SetCaretBlinkTime falhou. Error" & CStr (lErrorCode))92.   End If End If93.End Sub End Sub94. 95.Private Sub DisplayError(iFail As Integer) Private Sub DisplayError (ifail As Integer)96.   Dim sErrorMsg As String As String Dim sErrorMsg97.   lErrorCode = GetLastError lErrorCode = GetLastError98. 99.   Select Case iFail Selecione ifail Case100.       Case 0   ' GetCaretBlinkRate Function Failed Função GetCaretBlinkRate Case 0 'Falha101.          sErrorMsg = "GetCaretBlinkRate Failed. Error Code " sErrorMsg = "Falha GetCaretBlinkRate. Código de erro"102.          sErrorMsg = sErrorMsg & CStr(lErrorCode) sErrorMsg = sErrorMsg & CStr (lErrorCode)103.       Case 1 Caso 1104.          sErrorMsg = "SetCaretBlinkRate Failed. Error Code " sErrorMsg = "Falha SetCaretBlinkRate. Código de erro"105.          sErrorMsg = sErrorMsg & CStr(lErrorCode) sErrorMsg = sErrorMsg & CStr (lErrorCode)106.       Case Else Case Else107.          sErrorMsg = "Unknown Error" sErrorMsg = "Erro desconhecido"108.    End Select End Select109.  110.    MsgBox (sErrorMsg) MsgBox (sErrorMsg)111. End Sub End Sub

  1. On the Run menu, click Start or press the F5 key to start the program. No menu executar, clique em Iniciar ou pressione a tecla F5 para iniciar o programa. Move the scroll bar to change the cursor blink rate. Mova a barra de scroll para alterar a taxa de intermitência do cursor. You can also enter a number between 10 and 1000 in the TextBox to change the blink rate. Você também pode inserir um número entre 10 e 1000 no TextBox para alterar a taxa de intermitência. Click the "Return to Default" button to set the blink rate back to the default setting. Clique no "Return to Default" para definir a taxa de intermitência de volta para a configuração padrão. To exit the application, you should click the Close button at the far right of the title bar instead of the stop button in the Visual Basic environment. Para sair do aplicativo, você deve clicar no botão Fechar no lado direito da barra de título em vez do botão de parada no ambiente do Visual Basic. This will restore your original cursor blink rate. Isso irá restaurar a sua taxa de intermitência do cursor original.


Back to the top Voltar ao topo

Tips Dicas



  • Save your work often: because you are calling functions in the Windows API, you are bypassing the syntax checking feature of Visual Basic. Salve o seu trabalho muitas vezes: porque você está chamando funções na API do Windows, você evita o recurso de verificação da sintaxe do Visual Basic. If the function fails, then an application error can occur and lock up your system. Se a função falhar, um erro de aplicativo pode ocorrer e trava o sistema. You can set Visual Basic to always save your work prior to running the project by enabling the Prompt to Save Changes option in the Environment Tab of the Options dialog box. Você pode configurar o Visual Basic para sempre salvar seu trabalho antes de executar o projeto, permitindo que o Prompt to Save Changes opção na guia Ambiente da caixa de diálogo Opções. You can get to this dialog box by clicking Options from the Tools menu. Você pode obter esta caixa de diálogo clicando em Opções do menu Ferramentas.

  • Specify the variable type explicitly rather than using the Any variable type; a number of functions in the API Text Viewer can accept any type of variable as a parameter. Especifique o tipo de variável explicitamente em vez de usar o tipo de qualquer variável, um número de funções na API Text Viewer pode aceitar qualquer tipo de variável como um parâmetro. These functions have parameters declared as Any. Estas funções têm parâmetros declarados como qualquer outro. You can change the parameter to as specified variable type in order to simplify debugging your code. Você pode mudar o parâmetro de tipo variável, conforme especificado a fim de simplificar a depuração de seu código.

  • Verify that you are passing the correct variable types, constants, and values required by the function by checking the function documentation in the Platform SDK. Verifique se você estiver passando os tipos de variáveis corretas, constantes e valores exigidos pela função verificando a documentação da função no Plataforma SDK. Although the SDK was written for a C programmer and therefore uses C data types, you can pass the appropriate data types by using the following Visual Basic data types: Embora o SDK foi escrito por um programador C e, portanto, usa tipos de dados C, você pode passar os tipos de dados adequadas, utilizando os seguintes dados Visual Basic tipos:

































































































Function Data Type Parameter Função do parâmetro tipo de dados Appropriate Visual Basic Data Type Tipo adequada Visual Basic Data
int, INT int, INTByVal Long ByVal Long
UNINT UNINTByVal Long ByVal Long
BOOL BOOLByVal Long ByVal Long
WORD WORDByVal Integer ByVal Inteiro
DWORD DWORDByVal Long ByVal Long
WPARAM WPARAMByVal Long ByVal Long
LPARAM, LRESULT LPARAM, LRESULTByVal Long ByVal Long
COLORREF COLORREFByVal Long ByVal Long
ATOM ATOMByVal Integer ByVal Inteiro
HANDLE HANDLEByVal Long ByVal Long
BYTE BYTEByVal Byte ByVal Byte
char charByVal Byte ByVal Byte
LPINT, int * LPINT, int *ByRef Long ByRef Long
LPUINT, UINT * LPUINT, UINT *ByRef Long ByRef Long
LPBOOL, BOOL * LPBOOL, BOOL *ByRef Long ByRef Long
LPBYTE, BYTE * LPBYTE, BYTE *ByRef Byte ByRef Byte
LPWORD, WORD * LPWORD, WORD *ByRef Integer ByRef Inteiro
LPDWORD, DWORD * LPDWORD, DWORD *ByRef Long ByRef Long
LPHANDLE, HANDLE * LPHANDLE, HANDLE *ByRef Long ByRef Long



  • Use the Add-In Manager to add the API Text Viewer as an add-in to the IDE. Use o Add-In Manager para adicionar o API Text Viewer como um add-in para o IDE. To use the Add-In Manager, see Using Wizards and Add-Ins in "Chapter 4-Managing Projects" of the "Visual Basic Programmer's Guide." Para usar o Add-In Manager, consulte Usando assistentes e Add-Ins no "Capítulo 4, Gerenciamento de Projetos" do Guia do "Programador Visual Basic."

  • When using the API Text Viewer, convert the API text file to an Access database for faster searches. Ao utilizar o API Text Viewer, converter o texto API arquivo para um banco de dados para pesquisas mais rápidas.

  • Always pass strings to a DLL using the ByVal keyword. Sempre passe seqüências de caracteres para uma DLL usando a palavra-chave ByVal.


Back to the top Voltar ao topo

REFERENCES REFERÊNCIAS


For more information about using the functions in the Windows API, refer to the following sources: Para obter mais informações sobre como utilizar as funções na API do Windows, consulte as seguintes fontes:

  • VB5DLL.DOC - located in the TOOLS\DOCS directory of the Visual Basic product CD. VB5DLL.Doc - localizado no diretório \ DOCS TOOLS do produto CD do Visual Basic. These are notes for developing DLLs for use with Microsoft Visual Basic. Estas são notas para o desenvolvimento de DLLs para uso com o Microsoft Visual Basic. Use this information to know what a DLL expects from Visual Basic. Use essas informações para saber o que é uma DLL espera de Visual Basic.

  • "Visual Basic 5.0 Programmer's Guide to the Win32 API" by Dan Appleman-A "must" book for Visual Basic programmers who want to use the Windows API. "Visual Basic 5.0 Programmer's Guide to a API Win32" por Dan Appleman-Um "must" livro para programadores Visual Basic que querem usar a API do Windows. The book contains information written for the Visual Basic programmer on using the Windows API. O livro contém informações escritas para o programador de Visual Basic em usar a API do Windows.

  • Hardcore Visual Basic by Bruce McKinney-contains good examples on how to extend the capabilities of Visual Basic through the Windows API. Hardcore Visual Basic por Bruce McKinney contém bons exemplos sobre como estender as capacidades do Visual Basic através da API do Windows.

  • Microsoft Developer Network Subscription - contains the header files used to compile the DLLs used by the operating system. Microsoft Developer Network Assinatura - contém os arquivos de cabeçalho usados para compilar as DLLs utilizadas pelo sistema operacional. You can use this information to verify the correct function, type, and constant declarations. Você pode usar essa informação para verificar o correto funcionamento, tipo e declarações de constantes.

  • Mastering Visual Basic 5-Chapter 5: Using Dynamic Link Libraries: contains a good tutorial on using the Windows API. Dominando o Visual Basic 5 do capítulo 5: Usando o Dynamic Link Libraries: contém um bom tutorial sobre como usar a API do Windows.


For additional information on looking for the correct parameters, values, and constants required by the Windows API, please see the following article in the Microsoft Knowledge Base: Para obter informações adicionais sobre procurando os parâmetros corretos, os valores e as constantes exigidas pela API do Windows, consulte o seguinte artigo na Microsoft Knowledge Base:

187674 (http://support.microsoft.com/kb/187674/EN-US/ ) How To Find Undocumented Constants Used by Windows API Functions 187674 (http://support.microsoft.com/kb/187674/EN-US/) Como localizar Undocumented constantes usadas pelo Windows API funções

The following articles in the Microsoft Knowledge Base show you how to use functions in the Windows API to accomplish specific tasks: Os seguintes artigos na Microsoft Knowledge Base mostrar-lhe como utilizar as funções na API do Windows para realizar tarefas específicas:

161161 (http://support.microsoft.com/kb/161161/EN-US/ ) How To Search a ListBox Control Quickly 161161 (http://support.microsoft.com/kb/161161/EN-US/) Como procurar um ListBox controle rapidamente

175512 (http://support.microsoft.com/kb/175512/EN-US/ ) How To Get a Short Filename from a Long Filename 175512 (http://support.microsoft.com/kb/175512/EN-US/) Como obter um nome de arquivo curto de um nome de arquivo longo

151799 (http://support.microsoft.com/kb/151799/EN-US/ ) How To Use the Animated Copy Functions in Windows 95 151799 (http://support.microsoft.com/kb/151799/EN-US/) Como usar o Animated Funções de cópia em Windows 95

Back to the top Voltar ao topo
APPLIES TO Aplica-se a


  • Microsoft Visual Basic 6.0 Learning Edition Microsoft Learning Edition Visual Basic 6.0

  • Microsoft Visual Basic 6.0 Professional Edition Microsoft Visual Basic Professional Edition 6,0

  • Microsoft Visual Basic 5.0 Professional Edition Microsoft Visual Basic Professional Edition 5,0

  • Microsoft Visual Basic 6.0 Enterprise Edition Microsoft Visual Basic Edition 6.0 Enterprise

  • Microsoft Visual Basic 5.0 Enterprise Edition Edition Microsoft Visual Basic 5.0 Enterprise

  • Microsoft Visual Basic 4.0 Standard Edition Microsoft Visual Basic 4.0 Edição Standard

  • Microsoft Visual Basic 4.0 Professional Edition Microsoft Visual Basic Professional Edition 4,0

  • Microsoft Visual Basic 4.0 32-Bit Enterprise Edition Microsoft Visual Basic 4.0 Enterprise Edition 32-Bit

  • Microsoft Visual Basic for Applications 5.0 Microsoft Visual Basic for Applications 5,0


Back to the top Voltar ao topo








Keywords: Palavras-chave:

kbhowto kbapi kbfaq KB190000 kbhowto kbapi KB190000 kbfaq

Back to the top Voltar ao topo

 

Comentários

Postagens mais visitadas deste blog

Instalação NetBeans

Calcular frete pelos correios via PHP