INTRODUCCION A LAS API´s DE WINDOWs.
Primero que todo, API quiere decir Aplication Program Interface, o lo que es lo mismo Interfase para la programación de Aplicaciones. Las api son funciones ajenas a VB, por lo que tiene que buscar afuera (Windows) en dlls´s o en archivos .exe que trae Windows.
Como dijimos antes el mismo Windows nos deja acceder a las api, que usa para hacer distintas tareas como por ejemplo dejar una ventana Always on top, reiniciar el sistema, Acceder al registro y modificarlo, abrir la lectora de cd...etc (y si... como estas pensando se usan para hacer bromas también xD o daño en algunos casos). En sintesis hacer exactamente todo o casi todo lo que hace windows hacia el usuario.
El armado para llamar alguna función API consta de:
[PRIVATE] + 'DECLARE FUNCTION' + <NOMBREDELAFUNCION> + 'LIB' + <"LIBRERIA"> + 'ALIAS' + (Parametros)
Si la funcion necesita el uso de CONSTANTES es necesario declararlas antes.
Por ejemplo para obtener el nombre de la PC escribiríamos lo siguiente en un módulo para poder distinguir bien el codigo.....o escribirlo en el mismo Form (General) <Poco Recomendado>.-
Código:
Private Declare Function NombrePC Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Private Sub Form_Load()
Dim Cadena As String
Cadena = String(255, Chr$(0))
NombrePC Cadena, 255
Cadena = Left$(Cadena, InStr(1, Cadena, Chr$(0)))
MsgBox Cadena
End Sub
Private Sub Form_Load()
Dim Cadena As String
Cadena = String(255, Chr$(0))
NombrePC Cadena, 255
Cadena = Left$(Cadena, InStr(1, Cadena, Chr$(0)))
MsgBox Cadena
End Sub
Como se puede observar se uso la librería "Kernel32" (Es el núcleo del S.O), pero hay otras mas usadas como:
GDI32 > Funciones para manejar la parte gráfica y de pantalla
USER32 > Funciones de uso en general
ADVAPI32 > Funciones de nivel avanzado
WINMM > La parte sonido y multimedia
Shell32, nos sirve para ejecutar algo, por ejemplo abrir el Outlook Express para que alguien nos envie un mail, o abrir el explorador para que entre a un sitio determinado
otras: Comdlg32, winspool.drv, lz32, Ole32 etc.
Donde esta el Api Viewer?
Menu Inicio/Programas/Microsoft Visual Studio 6.0/Herramientas de Microsoft Visual Studio 6.0/(He aqui) Visor de Texto API >O su direccion equivalente en Inglés.
Como usar el api Viewer?
Una vez abierto el API Viewer, tenemos que cargar los datos (Archivos .txt) que trae, ponemos cargar archivo de texto, dependiendo de la pc va tener una pequeña tardanza por lo cual va a preguntar si queremos convertir a una BD para tener acceso mas rápido. Le ponemos si, y usamos, buscando en la parte superior de búsqueda.
Algunos Ejemplos Útiles
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Abrir Outlook para que nos envíen un mail
---------------
SHELL32
(Copialo tal cual y pegalo)
---------------
Código:
Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
Const SW_SHOWNORMAL = 1
Private Sub Form_Load()
ShellExecute Me.hwnd, vbNullString, "mailto:shadow_enn_357 @ Hotmail.com", vbNullString, "C:\", SW_SHOWNORMAL
End Sub
Const SW_SHOWNORMAL = 1
Private Sub Form_Load()
ShellExecute Me.hwnd, vbNullString, "mailto:shadow_enn_357 @ Hotmail.com", vbNullString, "C:\", SW_SHOWNORMAL
End Sub
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Para Obtener la Version de Windows
---------------
KERNEL32
(Copialo tal cual y pegalo)
---------------
Código:
Private Declare Function GetVersionEx Lib "kernel32" Alias "GetVersionExA" (lpVersionInformation As OSVERSIONINFO) As Long
Private Type OSVERSIONINFO
dwOSVersionInfoSize As Long
dwMajorVersion As Long
dwMinorVersion As Long
dwBuildNumber As Long
dwPlatformId As Long
szCSDVersion As String * 128
End Type
Private Sub Form_Load()
Dim OSInfo As OSVERSIONINFO, PId As String
Me.AutoRedraw = True
'Set the structure size
OSInfo.dwOSVersionInfoSize = Len(OSInfo)
'Get the Windows version
Ret& = GetVersionEx(OSInfo)
'Chack for errors
If Ret& = 0 Then MsgBox "Error Getting Version Information": Exit Sub
'Print the information to the form
Select Case OSInfo.dwPlatformId
Case 0
PId = "Windows 32s "
Case 1
PId = "Windows 95/98"
Case 2
PId = "Windows NT "
End Select
Print "OS: " + PId
Print "Win version:" + Str$(OSInfo.dwMajorVersion) + "." + LTrim(Str(OSInfo.dwMinorVersion))
Print "Build: " + Str(OSInfo.dwBuildNumber)
End Sub
Private Type OSVERSIONINFO
dwOSVersionInfoSize As Long
dwMajorVersion As Long
dwMinorVersion As Long
dwBuildNumber As Long
dwPlatformId As Long
szCSDVersion As String * 128
End Type
Private Sub Form_Load()
Dim OSInfo As OSVERSIONINFO, PId As String
Me.AutoRedraw = True
'Set the structure size
OSInfo.dwOSVersionInfoSize = Len(OSInfo)
'Get the Windows version
Ret& = GetVersionEx(OSInfo)
'Chack for errors
If Ret& = 0 Then MsgBox "Error Getting Version Information": Exit Sub
'Print the information to the form
Select Case OSInfo.dwPlatformId
Case 0
PId = "Windows 32s "
Case 1
PId = "Windows 95/98"
Case 2
PId = "Windows NT "
End Select
Print "OS: " + PId
Print "Win version:" + Str$(OSInfo.dwMajorVersion) + "." + LTrim(Str(OSInfo.dwMinorVersion))
Print "Build: " + Str(OSInfo.dwBuildNumber)
End Sub
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Dibujo y Formas
>Necesita *Dos Timer con Intervalo =100 un *Command Button
---------------
GDI32
(Copialo tal cual y pegalo)
---------------
Código:
Private Type POINTAPI
x As Long
y As Long
End Type
Private Declare Function GetActiveWindow Lib "user32" () As Long
Private Declare Function GetWindowDC Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function Ellipse Lib "gdi32" (ByVal hdc As Long, ByVal X1 As Long, ByVal Y1 As Long, ByVal X2 As Long, ByVal Y2 As Long) As Long
Private Declare Function TextOut Lib "gdi32" Alias "TextOutA" (ByVal hdc As Long, ByVal x As Long, ByVal y As Long, ByVal lpString As String, ByVal nCount As Long) As Long
Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
Private Sub Form_Load()
Timer1.Interval = 100
Timer1.Enabled = True
Timer2.Interval = 100
Timer2.Enabled = True
Command1.Caption = "Draw Text"
End Sub
'This will draw an Ellipse on the active window
Sub Timer1_Timer()
Dim Position As POINTAPI
'Get the cursor position
GetCursorPos Position
'Draw the Ellipse on the Screen's DC
Ellipse GetWindowDC(0), Position.x - 5, Position.y - 5, Position.x + 5, Position.y + 5
End Sub
Sub Command1_Click()
Dim intCount As Integer, strString As String
strString = "Cool, text on screen !"
For intCount = 0 To 30
'Draw the text on the screen
TextOut GetWindowDC(0), intCount * 20, intCount * 20, strString, Len(strString)
Next intCount
End Sub
Private Sub Timer2_Timer()
'Draw the text to the active window
TextOut GetWindowDC(GetActiveWindow), 50, 50, "This is a form", 14
End Sub
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*x As Long
y As Long
End Type
Private Declare Function GetActiveWindow Lib "user32" () As Long
Private Declare Function GetWindowDC Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function Ellipse Lib "gdi32" (ByVal hdc As Long, ByVal X1 As Long, ByVal Y1 As Long, ByVal X2 As Long, ByVal Y2 As Long) As Long
Private Declare Function TextOut Lib "gdi32" Alias "TextOutA" (ByVal hdc As Long, ByVal x As Long, ByVal y As Long, ByVal lpString As String, ByVal nCount As Long) As Long
Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
Private Sub Form_Load()
Timer1.Interval = 100
Timer1.Enabled = True
Timer2.Interval = 100
Timer2.Enabled = True
Command1.Caption = "Draw Text"
End Sub
'This will draw an Ellipse on the active window
Sub Timer1_Timer()
Dim Position As POINTAPI
'Get the cursor position
GetCursorPos Position
'Draw the Ellipse on the Screen's DC
Ellipse GetWindowDC(0), Position.x - 5, Position.y - 5, Position.x + 5, Position.y + 5
End Sub
Sub Command1_Click()
Dim intCount As Integer, strString As String
strString = "Cool, text on screen !"
For intCount = 0 To 30
'Draw the text on the screen
TextOut GetWindowDC(0), intCount * 20, intCount * 20, strString, Len(strString)
Next intCount
End Sub
Private Sub Timer2_Timer()
'Draw the text to the active window
TextOut GetWindowDC(GetActiveWindow), 50, 50, "This is a form", 14
End Sub
Obtiene Nombre de Usuario
>Necesita un control Timer
---------------
ADVAPI32
(Copialo tal cual y pegalo)
---------------
Código:
Private Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" (ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long
Private Declare Function IsIconic Lib "user32" (ByVal hwnd As Long) As Long
Private Sub Form_Load()
Timer1.Interval = 100
Timer1.Enabled = True
Dim strTemp As String, strUserName As String
'Create a buffer
strTemp = String(100, Chr$(0))
'Get the temporary path
GetTempPath 100, strTemp
'strip the rest of the buffer
strTemp = Left$(strTemp, InStr(strTemp, Chr$(0)) - 1)
'Create a buffer
strUserName = String(100, Chr$(0))
'Get the username
GetUserName strUserName, 100
'strip the rest of the buffer
strUserName = Left$(strUserName, InStr(strUserName, Chr$(0)) - 1)
'Show the temppath and the username
MsgBox "Hello " + strUserName + Chr$(13) + "The temp. path is " + strTemp
End Sub
Private Sub Timer1_Timer()
Dim Boo As Boolean
'Check if this form is minimized
Boo = IsIconic(Me.hwnd)
'Update the form's caption
Me.Caption = "Form minimized: " + Str$(Boo)
End Sub
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" (ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long
Private Declare Function IsIconic Lib "user32" (ByVal hwnd As Long) As Long
Private Sub Form_Load()
Timer1.Interval = 100
Timer1.Enabled = True
Dim strTemp As String, strUserName As String
'Create a buffer
strTemp = String(100, Chr$(0))
'Get the temporary path
GetTempPath 100, strTemp
'strip the rest of the buffer
strTemp = Left$(strTemp, InStr(strTemp, Chr$(0)) - 1)
'Create a buffer
strUserName = String(100, Chr$(0))
'Get the username
GetUserName strUserName, 100
'strip the rest of the buffer
strUserName = Left$(strUserName, InStr(strUserName, Chr$(0)) - 1)
'Show the temppath and the username
MsgBox "Hello " + strUserName + Chr$(13) + "The temp. path is " + strTemp
End Sub
Private Sub Timer1_Timer()
Dim Boo As Boolean
'Check if this form is minimized
Boo = IsIconic(Me.hwnd)
'Update the form's caption
Me.Caption = "Form minimized: " + Str$(Boo)
End Sub
Reiniciar PC
-----------
USER32
(Copialo tal cual y pegalo)
----------
Código:
Const EWX_LOGOFF = 0
Const EWX_SHUTDOWN = 1
Const EWX_REBOOT = 2
Const EWX_FORCE = 4
Private Declare Function ExitWindowsEx Lib "user32" (ByVal uFlags As Long, ByVal dwReserved As Long) As Long
Private Sub Form_Load()
msg = MsgBox("This program is going to reboot your computer. Press OK to continue or Cancel to stop.", vbCritical + vbOKCancel + 256, App.Title)
If msg = vbCancel Then End
'reboot the computer
ret& = ExitWindowsEx(EWX_FORCE Or EWX_REBOOT, 0)
End Sub
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*Const EWX_SHUTDOWN = 1
Const EWX_REBOOT = 2
Const EWX_FORCE = 4
Private Declare Function ExitWindowsEx Lib "user32" (ByVal uFlags As Long, ByVal dwReserved As Long) As Long
Private Sub Form_Load()
msg = MsgBox("This program is going to reboot your computer. Press OK to continue or Cancel to stop.", vbCritical + vbOKCancel + 256, App.Title)
If msg = vbCancel Then End
'reboot the computer
ret& = ExitWindowsEx(EWX_FORCE Or EWX_REBOOT, 0)
End Sub
By
Shadow
2003
Nota1:
Algunos ejemplos Fueron sacados del API guide.
Nota2:
Me puedo haber equivocado en algo...o en todo, se aceptan sugerencias.
Función Api que permite abrir y cerrar el lector de CD.
Código:
'Api para incluir en un modulo
Declare Function mciSendString Lib "winmm.dll" Alias _
"mciSendStringA" (ByVal lpstrCommand As String, ByVal _
lpstrReturnString As String, ByVal uReturnLength As Long, _
ByVal hwndCallback As Long) As Long
'crear dos botones en un formulario
Private Sub Command1_Click()
'Se abrirá el CD
retvalue = mciSendString("set Cdaudio door open", returnstring, 127, 0)
End Sub
Private Sub Command2_Click()
'Se cerrará el CD
retvalue = mciSendString("set Cdaudio door closed", returnstring, 127, 0)
End Sub
Declare Function mciSendString Lib "winmm.dll" Alias _
"mciSendStringA" (ByVal lpstrCommand As String, ByVal _
lpstrReturnString As String, ByVal uReturnLength As Long, _
ByVal hwndCallback As Long) As Long
'crear dos botones en un formulario
Private Sub Command1_Click()
'Se abrirá el CD
retvalue = mciSendString("set Cdaudio door open", returnstring, 127, 0)
End Sub
Private Sub Command2_Click()
'Se cerrará el CD
retvalue = mciSendString("set Cdaudio door closed", returnstring, 127, 0)
End Sub