76
Trucos Breves Como crear un grupo de programas: Muy útil para crear instalaciones por ejemplo: Añadir un textbox y hacerlo oculto. Una vez oculto, escribir estas líneas sustituyendo "Nombre del Grupo" por que que se desea crear, y que lo colocamos en Inicio -> Programas. Private Sub Command1_Click() Text1.LinkTopic = "Progman|Progman" Text1.LinkMode = 2 Text1.LinkExecute "[CreateGroup(" + "Nombre del Grupo" + ")]" End Sub Vaciar la carpeta de Documentos de Windows: Inicie un nuevo proyecto y añada el siguiente código: Private Declare Function SHAddToRecentDocs Lib "Shell32" (ByVal lFlags As Long, ByVal lPv As Long) As Long Private Sub Form_Load() SHAddToRecentDocs 0, 0 End Sub Abrir la ventana de Propiedades de agregar o quitar aplicaciones: Añada el siguiente código: Private Sub Command1_Click() X = Shell("Rundll32.exe shell32.dll,Control_RunDLL appwiz.cpl @0") End Sub Uso de Random: La función Rnd o Random posee la virtud de obtener números aleatorios entre 0 y 1: El único inconveniente a la hora de usar Rnd, es que hay que inicializarlo, en otro caso, el resultado de la función Rnd, será siempre el mismo dentro de un determinado ordenador. Por ejemplo, el código: Private Sub Form_Load() Dim Num As Double Num = Rnd MsgBox Num End Sub

Trucos Breves VB

Embed Size (px)

Citation preview

  • Trucos Breves

    Como crear un grupo de programas:

    Muy til para crear instalaciones por ejemplo:

    Aadir un textbox y hacerlo oculto. Una vez oculto, escribir estas lneas sustituyendo "Nombre del Grupo" por que que se desea crear, y que lo colocamos en Inicio -> Programas. Private Sub Command1_Click() Text1.LinkTopic = "Progman|Progman" Text1.LinkMode = 2 Text1.LinkExecute "[CreateGroup(" + "Nombre del Grupo" + ")]" End Sub

    Vaciar la carpeta de Documentos de Windows:

    Inicie un nuevo proyecto y aada el siguiente cdigo:

    Private Declare Function SHAddToRecentDocs Lib "Shell32" (ByVal lFlags As Long, ByVal lPv As Long) As Long

    Private Sub Form_Load() SHAddToRecentDocs 0, 0 End Sub

    Abrir la ventana de Propiedades de agregar o quitar aplicaciones:

    Aada el siguiente cdigo:

    Private Sub Command1_Click() X = Shell("Rundll32.exe shell32.dll,Control_RunDLL appwiz.cpl @0") End Sub

    Uso de Random:

    La funcin Rnd o Random posee la virtud de obtener nmeros aleatorios entre 0 y 1:

    El nico inconveniente a la hora de usar Rnd, es que hay que inicializarlo, en otro caso, el resultado de la funcin Rnd, ser siempre el mismo dentro de un determinado ordenador. Por ejemplo, el cdigo:

    Private Sub Form_Load() Dim Num As Double Num = Rnd MsgBox Num End Sub

  • Nos dara como resultado siempre el mismo nmero.

    Para solucionar este problema, debemos escribir la sentencia Randomize antes de llamar a la funcin Rnd. De esta manera, la funcin Rnd actuar correctamente.

    El cdigo quedara as:

    Private Sub Form_Load() Dim Num As Double Randomize Num = Rnd MsgBox Num End Sub

    Calcular la etiqueta o label de un disco duro:

    Hallar la etiqueta o label del mismo disco duro:

    Escribir el siguiente cdigo:

    Private Declare Function GetVolumeInformation& Lib "kernel32" Alias "GetVolumeInformationA" (ByVal lpRootPathName As String, ByVal pVolumeNameBuffer As String, ByVal nVolumeNameSize As Long, lpVolumeSerialNumber As Long, lpMaximumComponentLength As Long, lpFileSystemFlags As Long, ByVal lpFileSystemNameBuffer As String, ByVal nFileSystemNameSize As Long)

    Private Sub Form_Load() Dim cad1 As String * 256 Dim cad2 As String * 256 Dim numSerie As Long Dim longitud As Long Dim flag As Long unidad = "D:\" Call GetVolumeInformation(unidad, cad1, 256, numSerie, longitud, flag, cad2, 256) MsgBox "Label de la unidad " & unidad & " = " & cad1 End Sub

    Imprimir un RichTextBox tal y como se ve:

    Imprimir un RichTextBox con su formato original.

    Private Sub Command1_Click() On Error GoTo ErrorDeImpresion Printer.Print "" RichTextBox1.SelPrint Printer.hDC Printer.EndDoc Exit Sub ErrorDeImpresion: Exit Sub

  • End Sub

    Otra forma:

    En el Formulario [Form1 por defecto] : Private Sub Form_Load() Dim LineWidth As Long Me.Caption = "Rich Text Box Ejemplo de Impresion" Command1.Move 10, 10, 600, 380 Command1.Caption = "&Imprimir" RichTextBox1.SelFontName = "Arial" RichTextBox1.SelFontSize = 10 LineWidth = WYSIWYG_RTF(RichTextBox1, 1440, 1440) Me.Width = LineWidth + 200 End Sub

    Private Sub Form_Resize() RichTextBox1.Move 100, 500, Me.ScaleWidth - 200, Me.ScaleHeight - 600 End Sub

    Private Sub Command1_Click() PrintRTF RichTextBox1, 1440, 1440, 1440, 1440 End Sub

    Crear un mdulo y escribir:

    Private Type Rect Left As Long Top As Long Right As Long Bottom As Long End Type

    Private Type CharRange cpMin As Long cpMax As Long End Type

    Private Type FormatRange hdc As Long hdcTarget As Long rc As Rect rcPage As Rect chrg As CharRange End Type

    Private Const WM_USER As Long = &H400 Private Const EM_FORMATRANGE As Long = WM_USER + 57 Private Const EM_SETTARGETDEVICE As Long = WM_USER + 72 Private Const PHYSICALOFFSETX As Long = 112 Private Const PHYSICALOFFSETY As Long = 113 Private Declare Function GetDeviceCaps Lib "gdi32" ( _ ByVal hdc As Long, ByVal nIndex As Long) As Long Private Declare Function SendMessage Lib "USER32" Alias "SendMessageA" _ (ByVal hWnd As Long, ByVal msg As Long, ByVal wp As Long, lp As Any) As Long

  • Private Declare Function CreateDC Lib "gdi32" Alias "CreateDCA" _ (ByVal lpDriverName As String, ByVal lpDeviceName As String, _ ByVal lpOutput As Long, ByVal lpInitData As Long) As Long

    Public Function WYSIWYG_RTF(RTF As RichTextBox, LeftMarginWidth As Long, _ RightMarginWidth As Long) As Long Dim LeftOffset As Long, LeftMargin As Long, RightMargin As Long Dim LineWidth As Long Dim PrinterhDC As Long Dim r As Long Printer.Print Space(1) Printer.ScaleMode = vbTwips LeftOffset = Printer.ScaleX(GetDeviceCaps(Printer.hdc, _ PHYSICALOFFSETX), vbPixels, vbTwips) LeftMargin = LeftMarginWidth - LeftOffset RightMargin = (Printer.Width - RightMarginWidth) - LeftOffset LineWidth = RightMargin - LeftMargin PrinterhDC = CreateDC(Printer.DriverName, Printer.DeviceName, 0, 0) r = SendMessage(RTF.hWnd, EM_SETTARGETDEVICE, PrinterhDC, _ ByVal LineWidth) Printer.KillDoc WYSIWYG_RTF = LineWidth End Function

    Public Sub PrintRTF(RTF As RichTextBox, LeftMarginWidth As Long, _ TopMarginHeight, RightMarginWidth, BottomMarginHeight) Dim LeftOffset As Long, TopOffset As Long Dim LeftMargin As Long, TopMargin As Long Dim RightMargin As Long, BottomMargin As Long Dim fr As FormatRange Dim rcDrawTo As Rect Dim rcPage As Rect Dim TextLength As Long Dim NextCharPosition As Long Dim r As Long Printer.Print Space(1) Printer.ScaleMode = vbTwips LeftOffset = Printer.ScaleX(GetDeviceCaps(Printer.hdc, _ PHYSICALOFFSETX), vbPixels, vbTwips) TopOffset = Printer.ScaleY(GetDeviceCaps(Printer.hdc, _ PHYSICALOFFSETY), vbPixels, vbTwips) LeftMargin = LeftMarginWidth - LeftOffset TopMargin = TopMarginHeight - TopOffset RightMargin = (Printer.Width - RightMarginWidth) - LeftOffset BottomMargin = (Printer.Height - BottomMarginHeight) - TopOffset rcPage.Left = 0 rcPage.Top = 0 rcPage.Right = Printer.ScaleWidth rcPage.Bottom = Printer.ScaleHeight rcDrawTo.Left = LeftMargin rcDrawTo.Top = TopMargin rcDrawTo.Right = RightMargin rcDrawTo.Bottom = BottomMargin fr.hdc = Printer.hdc fr.hdcTarget = Printer.hdc fr.rc = rcDrawTo

  • fr.rcPage = rcPage fr.chrg.cpMin = 0 fr.chrg.cpMax = -1 TextLength = Len(RTF.Text) Do NextCharPosition = SendMessage(RTF.hWnd, EM_FORMATRANGE, True, fr) If NextCharPosition >= TextLength Then Exit Do fr.chrg.cpMin = NextCharPosition Printer.NewPage Printer.Print Space(1) fr.hDC = Printer.hDC fr.hDCTarget = Printer.hDC Loop Printer.EndDoc r = SendMessage(RTF.hWnd, EM_FORMATRANGE, False, ByVal CLng(0)) End Sub

    Como obtener el directorio desde donde estamos ejecutando nuestro programa:

    Escribir el siguiente cdigo:

    Private Sub Form_Load() Dim Directorio as String ChDir App.Path ChDrive App.Path Directorio = App.Path If Len(Directorio) > 3 Then Directorio = Directorio & "\" End If End Sub

    Determinar si un fichero existe o no:

    Escriba el siguiente cdigo: (una de tanta maneras aparte de Dir$())

    Private Sub Form_Load() On Error GoTo Fallo x = GetAttr("C:\Autoexec.bat") MsgBox "El fichero existe." Exit Sub Fallo: MsgBox "El fichero no existe." End Sub

    Capturar la pantalla entera o la ventana activa:

  • Aadir dos botones y escribir el siguiente cdigo:

    Private Declare Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)

    Private Sub Command1_Click() 'Captura la ventana activa keybd_event 44, 0, 0&, 0& End Sub

    Private Sub Command2_Click() 'Captura toda la pantalla keybd_event 44, 1, 0&, 0& End Sub

    Salvar el contenido de un TextBox a un fichero en disco:

    Aada el siguiente cdigo:

    Private Sub Command1_Click() Dim canalLibre As Integer 'Obtenemos un canal libre que nos dar 'el sistema oparativo para poder operar canalLibre = FreeFile 'Abrimos el fichero en el canal dado Open "C:\fichero.txt" For Output As #canalLibre 'Escribimos el contenido del TextBox al fichero Print #canalLibre, Text1 Close #canalLibre End Sub

    Como desplegar la lista de un ComboBox automticamente:

    Insertar un ComboBox y un Botn en un nuevo proyecto y escribir el siguiente cdigo:

    Private Declare Function SendMessageLong Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long

    Private Sub Form_Load() Combo1.Clear Combo1.AddItem "Objeto 1" Combo1.AddItem "Objeto 2" Combo1.AddItem "Objeto 3" Combo1.AddItem "Objeto 4" Combo1.AddItem "Objeto 5" Combo1.AddItem "Objeto 6" Combo1.AddItem "Objeto 7" Combo1.Text = "Objeto 1"

  • End Sub

    Private Sub Command1_Click() 'ComboBox desplegado Dim Resp As Long Resp = SendMessageLong(Combo1.hwnd, &H14F, True, 0) End Sub

    Nota: Resp = SendMessageLong(Combo1.hwnd, &H14F, False, 0) oculta la lista desplegada de un ComboBox, aunque esto sucede tambin cuando cambiamos el focus a otro control o al formulario.

    Seleccin y eliminacin de todos los elementos de un ListBox:

    Insertar un ListBox y dos Botn en un nuevo proyecto. Poner la propiedad MultiSelect del ListBox a "1 - Simple" y escriba el siguiente cdigo:

    Private Declare Function SendMessageLong Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long

    Private Sub Form_Load() List1.AddItem "Texto 1" List1.AddItem "Texto 2" List1.AddItem "Texto 3" List1.AddItem "Texto 4" List1.AddItem "Texto 5" List1.AddItem "Texto 6" List1.AddItem "Texto 7" End Sub

    Private Sub Command1_Click() 'Seleccion de todo el contenido Dim Resp As Long Resp = SendMessageLong(List1.hwnd, &H185&, True, -1) End Sub

    Private Sub Command2_Click() 'Eliminacion de todos los elementos seleccionados Dim Resp As Long Resp = SendMessageLong(List1.hwnd, &H185&, False, -1) End Sub

    Calcular el tamao de fuentes de letra:

    Es til para utilizar con la propiedad Resize sobre los controles al cambiar de resolucin de pantalla. Escribir el siguiente cdigo:

    Private Declare Function GetDeviceCaps Lib "gdi32" (ByVal hdc As Long, ByVal nIndex As Long) As Long

  • Private Declare Function GetDC Lib "user32" (ByVal hwnd As Long) As Long Private Declare Function GetDesktopWindow Lib "user32" () As Long

    Private Sub Form_Load() Dim ObCaps As Long Dim ObDC As Long Dim ObDesktop As Long Dim Cad As String ObDesktop = GetDesktopWindow() ObDC = GetDC(ObDesktop) ObCaps = GetDeviceCaps(ObDC, 88) If ObCaps = 96 Then Cad = "Pequeas If ObCaps = 120 Then Cad = "Grandes" MsgBox "Fuentes de letra " & Cad End Sub

    *) Esta funcin ha sido corregida por un error en las etiquetas, 96 corresponde a pequeas y 120 a Grandes, agradecimientos a Andrs Moral Gutirrez por su correcin (01/06/1998)

    Provocar la trasparencia de un formulario:

    Escribir el siguiente cdigo:

    Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long

    Private Sub Form_Load() Dim Resp As Long Resp = SetWindowLong(Me.hwnd, -20, &H20&) Form1.Refresh End Sub

    Pasar de un TextBox a otro al pulsar Enter:

    Insertar tres TextBox y escribir el siguiente cdigo:

    Private Sub Text1_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then SendKeys "{tab}" KeyAscii = 0 End If End Sub

    Private Sub Text2_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then SendKeys "{tab}" KeyAscii = 0 End If

  • End Sub

    Private Sub Text3_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then SendKeys "{tab}" KeyAscii = 0 End If End Sub

    otra forma:

    Insertar tres TextBox, cambiar la propiedad KeyPreview del formulario a True y escribir el siguiente cdigo:

    Private Sub Form_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then SendKeys "{tab}" KeyAscii = 0 End If End Sub

    Usar IF THEN ELSE ENDIF en una misma lnea:

    Insertar un CommandButton y un TextBox y escribir el siguiente cdigo:

    Private Sub Command1_Click() Dim I As Integer Dim A As String I = 3 A = IIf(I 1, "True", "False") Text1.Text = A End Sub

    Convertir un texto a maysculas o minsculas:

    Crear un formulario y situar un TextBox. Escribir:

    Private Sub Text1_Change() Dim I As Integer Text1.Text = UCase(Text1.Text) I = Len(Text1.Text) Text1.SelStart = I End Sub

    Presentar la ventana AboutBox (Acerca de) por defecto:

    Escribir el siguiente cdigo en el formulario:

  • Private Declare Function ShellAbout Lib "shell32.dll" Alias "ShellAboutA" (ByVal hwnd As Long, ByVal szApp As String, ByVal szOtherStuff As String, ByVal hIcon As Long) As Long

    Private Sub Command1_Click() Call ShellAbout(Me.hwnd, "Ttulo Programa", "Copyright 1997, Dueo de la aplicacin", Me.Icon) End Sub

    Incrementar un men en ejecucin:

    Abrir un proyecto nuevo, y haga doble click sobre el formulario. Meidante el gestr de mens escribir lo siguiente:

    Caption -> Editor Name -> MnuEditor Pulse Insertar y el botn "->" Caption -> Aadir Name -> MnuAadir Pulse Insertar Caption -> Quitar Name -> MnuQuitar Enabled -> False Pulse Insertar Caption -> Salir Name -> MnuSalir Pulse Insertar Caption -> - Name -> MnuIndex Index -> 0 Pulse Aceptar

    Escribir el siguiente cdigo en el formulario:

    Private ultElem As Integer

    Private Sub Form_Load() ultElem = 0 End Sub

    Private Sub MnuQuitar_Click() Unload MnuIndex(ultElem) ultElem = ultElem - 1 If ultElem = 0 Then MnuQuitar.Enabled = False End If End Sub

    Private Sub MnuSalir_Click() End End Sub

  • Private Sub MnuAadir_Click() ultElem = ultElem + 1 Load MnuIndex(ultElem) MnuIndex(ultElem).Caption = "Menu -> " + Str(ultElem) MnuQuitar.Enabled = True End Sub

    Cambiar el fondo de Windows desde Visual Basic:

    Crear un formulario y escribir:

    Private Declare Function SystemParametersInfo Lib "user32" Alias "SystemParametersInfoA" (ByVal uAction As Long, ByVal uParam As Long, ByVal lpvParam As Any, ByVal fuWinIni As Long) As Long

    Private Sub Form_Load() Dim fallo As Integer fallo = SystemParametersInfo(20, 0, "C:\WINDOWS\FONDO.BMP", 0) End Sub

    Calcular el nmero de colores de video del modo actual de Windows:

    Crear un formulario y un TextBox y escribir:

    Private Declare Function GetDeviceCaps Lib "gdi32" (ByVal hdc As Long, ByVal nIndex As Long) As Long

    Private Sub Form_Load() i = (2 ^ GetDeviceCaps(Form1.hdc, 12)) ^ GetDeviceCaps(Form1.hdc, 14) Text1.Text = CStr(i) & " colores." End Sub

    Ajustar un Bitmap a la pantalla:

    Crear un formulario con un BitMap cualquiera y una etiqueta o Label con los atributos que quiera.

    Escribir lo siguiente:

    Private Sub Form_Paint() Dim i As Integer For i = 0 To Form1.ScaleHeight Step Picture1.Height For j = 0 To Form1.ScaleWidth Step Picture1.Width PaintPicture Picture1, j, i, Picture1.Width, Picture1.Height Next Next End Sub

  • Private Sub Form_Resize() Picture1.Left = -(Picture1.Width + 200) Picture1.Top = -(Picture1.Height + 200) Label1.Top = 100 Label1.Left = 100 End Sub

    Detectar la unidad del CD-ROM:

    Si para instalar una aplicacin o ejecutar un determinado software necesitas saber si existe el CD-ROM:.

    Crear un formulario con una etiqueta y escribir lo siguiente:

    Option Explicit

    Private Declare Function GetDriveType Lib "kernel32" Alias "GetDriveTypeA" (ByVal nDrive As String) As Long Private Declare Function GetLogicalDriveStrings Lib "kernel32" Alias "GetLogicalDriveStringsA" (ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long Private Const DRIVE_REMOVABLE = 2 Private Const DRIVE_FIXED = 3 Private Const DRIVE_REMOTE = 4 Private Const DRIVE_CDROM = 5 Private Const DRIVE_RAMDISK = 6

    Function StripNulls(startStrg$) As String Dim c%, item$ c% = 1 Do If Mid$(startStrg$, c%, 1) = Chr$(0) Then item$ = Mid$(startStrg$, 1, c% - 1) startStrg$ = Mid$(startStrg$, c% + 1, Len(startStrg$)) StripNulls$ = item$ Exit Function End If c% = c% + 1 Loop End Function

    Private Sub Form_Load() Dim r&, allDrives$, JustOneDrive$, pos%, DriveType& Dim CDfound As Integer allDrives$ = Space$(64) r& = GetLogicalDriveStrings(Len(allDrives$), allDrives$) allDrives$ = Left$(allDrives$, r&) Do pos% = InStr(allDrives$, Chr$(0)) If pos% Then JustOneDrive$ = Left$(allDrives$, pos%) allDrives$ = Mid$(allDrives$, pos% + 1, Len(allDrives$))

  • DriveType& = GetDriveType(JustOneDrive$) If DriveType& = DRIVE_CDROM Then CDfound% = True Exit Do End If End If Loop Until allDrives$ = "" Or DriveType& = DRIVE_CDROM If CDfound% Then label1.Caption = "La unidad de CD-ROM corresponde a la unidad: " & UCase$(JustOneDrive$) Else label1.Caption = "Su sistema no posee CD-ROM o unidad no encontrada." End If End Sub

    Calcular la profundidad de color (bits por pixel) y resolucin de Windows:

    Crear un formulario y un TextBox y escribir:

    Private Declare Function GetDeviceCaps Lib "gdi32" (ByVal hdc As Long, ByVal nIndex As Long) As Long

    Private Sub Form_Load() Dim col, bit, largo, alto As Integer col = GetDeviceCaps(Form1.hdc, 12) If col = 1 Then bit = GetDeviceCaps(Form1.hdc, 14) If bit = 1 Then Text1.Text = "Resolucion de 1 bit / 2 colores" ElseIf bit = 4 Then Text1.Text = "Resolucion de 4 bits / 16 colores" End If ElseIf col = 8 Then Text1.Text = "Resolucion de 8 bits / 256 colores" ElseIf col = 16 Then Text1.Text = "Resolucion de 16 bits / 65000 colores" Else Text1.Text = "Resolucion de 16 M colores" End If largo = GetDeviceCaps(Form1.hdc, 8) alto = GetDeviceCaps(Form1.hdc, 10) Text1.Text = Text1.Text & " " & largo & "x" & alto & " pixels" End Sub

    Comprobar si el sistema posee tarjeta de sonido:

    Crear un formulario y escribir:

    Private Declare Function waveOutGetNumDevs Lib "winmm.dll" () As Long

  • Private Sub Form_Load() Dim inf As Integer inf = waveOutGetNumDevs() If inf > 0 Then MsgBox "Tarjeta de sonido soportada.", vbInformation, "Informacion: Tarjeta de sonido" Else MsgBox "Tarjeta de sonido no soportada.", vbInformation, "Informacion: Tarjeta de sonido" End If End End Sub

    Crear una ventana con la informacin del Sistema:

    Crear un formulario e insertar un mdulo y escribir en el formulario lo siguiente:

    Private Sub Form_Load() Dim msg As String MousePointer = 11 Dim verinfo As OSVERSIONINFO verinfo.dwOSVersionInfoSize = Len(verinfo) ret% = GetVersionEx(verinfo) If ret% = 0 Then MsgBox "Error Obteniendo Information de la Version" End End If Select Case verinfo.dwPlatformId Case 0 msg = msg + "Windows 32s " Case 1 msg = msg + "Windows 95 " Case 2 msg = msg + "Windows NT " End Select ver_major$ = verinfo.dwMajorVersion ver_minor$ = verinfo.dwMinorVersion build$ = verinfo.dwBuildNumber msg = msg + ver_major$ + "." + ver_minor$ msg = msg + " (Construido " + build$ + ")" + vbCrLf + vbCrLf Dim sysinfo As SYSTEM_INFO GetSystemInfo sysinfo msg = msg + "CPU: " Select Case sysinfo.dwProcessorType Case PROCESSOR_INTEL_386 msg = msg + "Procesador Intel 386 o compatible." + vbCrLf Case PROCESSOR_INTEL_486 msg = msg + "Procesador Intel 486 o compatible." + vbCrLf Case PROCESSOR_INTEL_PENTIUM msg = msg + "Procesador Intel Pentium o compatible." + vbCrLf Case PROCESSOR_MIPS_R4000 msg = msg + "Procesador MIPS R4000." + vbCrLf

  • Case PROCESSOR_ALPHA_21064 msg = msg + "Procesador DEC Alpha 21064." + vbCrLf Case Else msg = msg + "Procesador (desconocido)." + vbCrLf End Select msg = msg + vbCrLf Dim memsts As MEMORYSTATUS Dim memory& GlobalMemoryStatus memsts memory& = memsts.dwTotalPhys msg = msg + "Memoria Fisica Total: " msg = msg + Format$(memory& \ 1024, "###,###,###") + "Kb" + vbCrLf memory& = memsts.dwAvailPhys msg = msg + "Memoria Fisica Disponible: " msg = msg + Format$(memory& \ 1024, "###,###,###") + "Kb" + vbCrLf memory& = memsts.dwTotalVirtual msg = msg + "Memoria Virtual Total: " msg = msg + Format$(memory& \ 1024, "###,###,###") + "Kb" + vbCrLf memory& = memsts.dwAvailVirtual msg = msg + "Memoria Virtual Disponible: " msg = msg + Format$(memory& \ 1024, "###,###,###") + "Kb" + vbCrLf + vbCrLf MsgBox msg, 0, "Acerca del Sistema" MousePointer = 0 End End Sub

    Escribir lo siguiente en el mdulo:

    Type SYSTEM_INFO dwOemID As Long dwPageSize As Long lpMinimumApplicationAddress As Long lpMaximumApplicationAddress As Long dwActiveProcessorMask As Long dwNumberOrfProcessors As Long dwProcessorType As Long dwAllocationGranularity As Long dwReserved As Long End Type

    Type OSVERSIONINFO dwOSVersionInfoSize As Long dwMajorVersion As Long dwMinorVersion As Long dwBuildNumber As Long dwPlatformId As Long szCSDVersion As String * 128 End Type

    Type MEMORYSTATUS dwLength As Long dwMemoryLoad As Long dwTotalPhys As Long dwAvailPhys As Long dwTotalPageFile As Long dwAvailPageFile As Long

  • dwTotalVirtual As Long dwAvailVirtual As Long End Type

    Declare Function GetVersionEx Lib "kernel32" Alias "GetVersionExA" (LpVersionInformation As OSVERSIONINFO) As Long Declare Sub GlobalMemoryStatus Lib "kernel32" (lpBuffer As MEMORYSTATUS) Declare Sub GetSystemInfo Lib "kernel32" (lpSystemInfo As SYSTEM_INFO)

    Public Const PROCESSOR_INTEL_386 = 386 Public Const PROCESSOR_INTEL_486 = 486 Public Const PROCESSOR_INTEL_PENTIUM = 586 Public Const PROCESSOR_MIPS_R4000 = 4000 Public Const PROCESSOR_ALPHA_21064 = 21064

    Mostrar un fichero AVI a pantalla completa:

    Crear un formulario y escribir:

    Private Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA" (ByVal lpstrCommand As String, ByVal lpstrReturnString As Any, ByVal uReturnLength As Long, ByVal hwndCallback As Long) As Long

    Private Sub Form_Load() CmdStr$ = "play e:\media\avi\nombre.avi fullscreen" ReturnVal& = mciSendString(CmdStr$, 0&, 0, 0&) End Sub

    Crear un link con un programa aadindolo al grupo de programas situado en

    Inicio -> Programas o Start -> Programs:

    Crear un formulario y escribir:

    Private Declare Function fCreateShellLink Lib "STKIT432.DLL" (ByVal lpstrFolderName As String, ByVal lpstrLinkName As String, ByVal lpstrLinkPath As String, ByVal lpstrLinkArgs As String) As Long

    Private Sub Form_Load() iLong = fCreateShellLink("", "Visual Basic", "C:\Archivos de Programa\DevStudio\Vb\vb5.exe", "")

  • End Sub

    Apagar el equipo, reiniciar Windows, reiniciar el Sistema:

    Aadir tres botones a un formulario y escribir lo siguiente en el cdigo del formulario:

    Private Declare Function ExitWindowsEx& Lib "user32" (ByVal uFlags&, ByVal dwReserved&)

    Private Sub Command1_Click() Dim i as integer i = ExitWindowsEx(1, 0&) 'Apaga el equipo End Sub

    Private Sub Command2_Click() Dim i as integer i = ExitWindowsEx(0, 0&) 'Reinicia Windows con nuevo usuario End Sub

    Private Sub Command3_Click() Dim i as integer i = ExitWindowsEx(2, 0&) 'Reinicia el Sistema End Sub

    Borrar un fichero y enviarlo a la papelera de reciclaje:

    Crear un formulario y escribir el siguiente cdigo:

    Private Type SHFILEOPSTRUCT hWnd As Long wFunc As Long pFrom As String pTo As String fFlags As Integer fAnyOperationsAborted As Boolean hNameMappings As Long lpszProgressTitle As String End Type

    Private Declare Function SHFileOperation Lib "shell32.dll" Alias "SHFileOperationA" (lpFileOp As SHFILEOPSTRUCT) As Long

    Private Const FO_DELETE = &H3 Private Const FOF_ALLOWUNDO = &H40

    Public Sub PapeleraDeReciclaje(ByVal Fichero As String) Dim SHFileOp As SHFILEOPSTRUCT Dim RetVal As Long With SHFileOp .wFunc = FO_DELETE .pFrom = FileName

  • .fFlags = FOF_ALLOWUNDO End With RetVal = SHFileOperation(SHFileOp) End Sub

    Private Sub Form_Load() Recycle "c:\a.txt" End Sub

    El programa preguntar si deseamos o no eliminar el fichero y enviarlo a la papelera de reciclaje. El parmetro .fFlags nos permitir recuperar el fichero de la papelera si lo deseamos. Si eliminamos esta lnea, el fichero no podr ser recuperado.

    Abrir el Acceso telefnico a Redes de Windows y ejecutar una conexin:

    Crear un formulario y escribir el siguiente cdigo:

    Private Sub Form_Load() Dim AbrirConexion As Long AbrirConexion = Shell("rundll32.exe rnaui.dll,RnaDial " & "ConexinInternet", 1) SendKeys "{ENTER}" End Sub

    Situar una ScroolBar horizontal en un ListBox:

    Crear un formulario y escribir el siguiente cdigo:

    Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long

    Private Sub Form_Load() Dim x As Integer, i As Integer For i = 1 To 20 List1.AddItem "El nmero final de la seleccin es el " & i Next i x = SendMessage(List1.hwnd, &H194, 200, ByVal 0&) End Sub

    Obtener el nombre de usuario y de la compaia de Windows:

    Crear un formulario, aadir dos etiquetas o labels y escribir el siguiente cdigo:

    Private Declare Function RegQueryValueEx Lib "advapi32.dll" Alias "RegQueryValueExA" (ByVal hKey As Long, ByVal lpValueName As String,

  • ByVal lpReserved As Long, lpType As Long, lpData As Any, lpcbData As Long) As Long Private Declare Function RegOpenKey Lib "advapi32.dll" Alias "RegOpenKeyA" (ByVal hKey As Long, ByVal lpSubKey As String, phkResult As Long) As Long Private Declare Function RegCloseKey Lib "advapi32.dll" (ByVal hKey As Long) As Long

    Private Sub Form_Load() Dim strUser As String Dim strOrg As String Dim lngLen As Long Dim lngType As Long Dim hKey As Long Dim x As Long Const HKEY_LOCAL_MACHINE = &H80000002 Const REG_SZ = &H1 x = RegOpenKey(HKEY_LOCAL_MACHINE, "Software\Microsoft\Windows\CurrentVersion", hKey) ' open desired key in registry strUser = Space$(256) lngLen = Len(strUser) x = RegQueryValueEx(hKey, "RegisteredOwner", 0, lngType, ByVal strUser, lngLen) If x = 0 And lngType = REG_SZ And lngLen > 1 Then strUser = Left$(strUser, lngLen - 1) Else strUser = "Unknown" End If strOrg = Space$(256) lngLen = Len(strOrg) x = RegQueryValueEx(hKey, "RegisteredOrganization", 0, lngType, ByVal strOrg, lngLen) If x = 0 And lngType = REG_SZ And lngLen > 1 Then strOrg = Left$(strOrg, lngLen - 1) Else strOrg = "Unknown" End If Label1.Caption = "Usuario: " & strUser Label2.Caption = "Empresa: " & strOrg x = RegCloseKey(hKey) End Sub

    Forzar a un TextBox para que admita nicamente nmeros:

    Crear un formulario, aadir un TextBox y escribir el siguiente cdigo:

    Sub Text1_Keypress(KeyAscii As Integer) If KeyAscii Asc("9") Then 'KeyAscii = 8 es el retroceso o BackSpace If KeyAscii 8 Then KeyAscii = 0 End If

  • End If End Sub

    Forzar a un InputBox para que admita nicamente nmeros:

    Crear un formulario y escribir el siguiente cdigo:

    Private Sub Form_Load() Dim Numero As String Do Numero = InputBox("Introduzca un numero:") Loop Until IsNumeric(Numero) MsgBox "El numero es el " & Numero Unload Me End Sub

    Hacer Drag & Drop de un control (ejemplo de un PictureBox):

    En un formulario, aadir un PictureBox con una imagen cualquiera y escribir el siguiente cdigo:

    Private DragX As Integer Private DragY As Integer

    Sub Form_DragDrop(Source As Control, X As Single, Y As Single) Source.Move (X - DragX), (Y - DragY) End Sub

    Private Sub Picture1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) 'Si el boton del raton es el derecho, no hacemos nada If Button = 2 Then Exit Sub Picture1.Drag 1 DragX = X DragY = Y End Sub

    Private Sub Picture1_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) Picture1.Drag 2 End Sub

    Centrar una ventana en Visual Basic:

    Usar:

    Move (Screen.Width - Width) \ 2, (Screen.Height - Height) \ 2

    En vez de:

  • Form1.Left = Screen.Width - Width \ 2 Form1.Top = Screen.Height - Height \ 2

    Ejecuta pausas durante un determinado espacio de tiempo en segundos:

    Llamada: Espera(5)

    Sub Espera(Segundos As Single) Dim ComienzoSeg As Single Dim FinSeg As Single ComienzoSeg = Timer FinSeg = ComienzoSeg + Segundos Do While FinSeg > Timer DoEvents If ComienzoSeg > Timer Then FinSeg = FinSeg - 24 * 60 * 60 End If Loop End Sub

    Editor de texto:

    Seleccionar todo el texto: Text1.SetFocus Text1.SelStart = 0 Text1.SelLength = Len(Text1.Text)

    Copiar texto: Clipboard.Clear Clipboard.SetText Text1.SelText Text1.SetFocus

    Pegar texto: Text1.SelText = Clipboard.GetText() Text1.SetFocus

    Cortar texto: Clipboard.SetText Text1.SelText Text1.SelText = "" Text1.SetFocus

    Deshacer texto: (Nota: esta operacin slo es eficaz con el control Rich TextBox).

    En un mdulo copie esta lnea:

    Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal _ hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Long) As Long

    Esta es la instruccin de la funcin deshacer:

  • UndoResultado = SendMessage(Text1.hwnd, &HC7, 0&, 0&) If UndoResultado = -1 Then Beep MsgBox "Error al intentar recuperar.", 20, "Deshacer texto" End If

    Seleccionar todo el texto: SendKeys "^A"

    Copiar texto: SendKeys "^C"

    Pegar texto: SendKeys "^V"

    Cortar texto: SendKeys "^X"

    Deshacer texto: SendKeys "^Z"

    Obtener el directorio de Windows y el directorio de Sistema:

    En un mdulo copiar estas lneas:

    Declare Function GetSystemDirectory Lib "kernel32" Alias "GetSystemDirectoryA"_ (ByVal lpBuffer As String, ByVal nSize As Long) As Long Declare Function GetWindowsDirectory Lib "kernel32" Alias "GetWindowsDirectoryA"_ (ByVal lpBuffer As String, ByVal nSize As Long) As Long

    Ponga dos Labels o etiquetas y un botn en el formulario: Label1, Label2, Command1

    Hacer doble click sobre el botn y escribir el cdigo siguiente:

    Private Sub Command1_Click() Dim Car As String * 128 Dim Longitud, Es As Integer Dim Camino As String

    Longitud = 128

    Es = GetWindowsDirectory(Car, Longitud) Camino = RTrim$(LCase$(Left$(Car, Es))) Label1.Caption = Camino

    Es = GetSystemDirectory(Car, Longitud) Camino = RTrim$(LCase$(Left$(Car, Es))) Label2.Caption = Camino

    End Sub

  • Ocultar la barra de tareas en Windows 95 y/o Windows NT:

    En un mdulo copiar estas lneas:

    Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName_ As String, ByVal lpWindowName As String) As Long Declare Function SetWindowPos Lib "user32" (ByVal hwnd As Long, ByVal hWndInsertAfter As Long, ByVal x As Long, ByVal y As Long, ByVal cx As Long, ByVal cy As Long,_ ByVal wFlags As Long) As Long Global Ventana As Long Global Const Muestra = &H40 Global Const Oculta = &H80

    En un formulario ponga dos botones y escriba el cdigo correspondiente a cada uno de ellos:

    'Oculta la barra de tareas Private Sub Command1_Click() Ventana = FindWindow("Shell_traywnd", "") Call SetWindowPos(Ventana, 0, 0, 0, 0, 0, Oculta) End Sub

    'Muestra la barra de tareas Private Sub Command2_Click() Call SetWindowPos(Ventana, 0, 0, 0, 0, 0, Muestra) End Sub

    Imprimir el contenido de un TextBox en lneas de X caracteres:

    Aadir un TextBox con las propiedades "Multiline=True" y "ScrollBars=Vertical", y un CommandButton. Hacer doble click sobre l y escribir este cdigo:

    Private Sub Command1_Click() 'X es 60 en este ejmplo imprimeLineas Text1, 60 End Sub

    En las declaraciones "Generales" del formulario, escribimos:

    Public Sub imprimeLineas(Texto As Object, Linea As Integer) Dim Bloque As String 'Numero de caracteres = NumC 'Numero de Bloques = NumB Dim NumC, NumB As Integer NumC = Len(Texto.Text) If NumC > Linea Then NumB = NumC \ Linea For I = 0 To NumB Texto.SelStart = (Linea * I) Texto.SelLength = Linea

  • Bloque = Texto.SelText Printer.Print Bloque Next I Else Printer.Print Texto.Text End If Printer.EndDoc End Sub

    Leer y escribir un fichero Ini:

    Declaraciones generales en un mdulo:

    Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringA"_ (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpDefault As_ String ByVal lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As_ String) As Long Declare Function WritePrivateProfileString Lib "kernel32" Alias_ "WritePrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As_ Any, ByVal lpString As Any, ByVal lpFileName As String) As Long

    Leer en "Ejemplo.Ini":

    Private Sub Form_Load() Dim I As Integer Dim Est As String Est = String$(50, " ") I = GetPrivateProfileString("Ejemplo", "Nombre", "", Est, Len(Est), "Ejemplo.ini") If I > 0 Then MsgBox "Tu Nombre es: " & Est End If End Sub

    Escribir en "Prueba.Ini":

    Private Sub Form_Unload(Cancel As Integer) Dim I As Integer Dim Est As String Est = "Ejemplo - Apartado" I = WritePrivateProfileString("Ejemplo", "Nombre", Est, "Ejemplo.ini") End Sub

    (Nota: si I=0 quiere decir que no existe informacin en la lnea de fichero Ini a la que hacemos referencia. El fichero "Ejemplo.Ini" se crear automticamente).

    Crear una barra de estado sin utilizar controles OCX o VBX:

    Crear una PictureBox y una HScrollBar:

    Propiedades de la HScrollBar:

  • Max -> 100 Min -> 0

    Propiedades de la PictureBox: DrawMode -> 14 - Merge Pen Not FillColor -> &H00C00000& Font -> Arial; Negrita; 10 ForeColor -> &H00000000& ScaleHeight -> 10 ScaleMode -> 0 - User ScaleWidth -> 100

    Insertar en el formulario o mdulo el cdigo de la funcin:

    Sub Barra(Tam As Integer) If Tam > 100 Or Tam Insertar en el evento Change del control HScrollBar:

    Private Sub HScroll1_Change() Barra (HScroll1.Value) End Sub

    En el evento Paint del formulario, escribir:

    Private Sub Form_Paint() Barra (HScroll1.Value) End Sub

    Calcular el espacio total y espacio libre de una Unidad de disco:

    Crear un mdulo y escribir:

    Declare Function GetDiskFreeSpace Lib "kernel32" Alias "GetDiskFreeSpaceA"_ (ByVal lpRootPathName As String, lpSectorsPerCluster As Long, lpBytesPerSector_ As Long, lpNumberOfFreeClusters As Long, lpTtoalNumberOfClusters As Long) As Long

    Crear 7 Labels:

    Escribir el cdigo siguiente:

    Private Sub Form_Load() Dim I1 As Long Dim I2 As Long Dim I3 As Long Dim I4 As Long Dim Unidad As String Unidad = "C:/" GetDiskFreeSpace Unidad, I1, I2, I3, I4 Label1.Caption = Unidad Label2.Caption = I1 & " Sectores por cluster" Label3.Caption = I2 & " Bytes por sector" Label4.Caption = I3 & " Nmero de clusters libres"

  • Label5.Caption = I4 & " Nmero total de clusters" Label6.Caption = "Espacio total en disco: " & (I1 * I2 * I4) Label7.Caption = "Espacio libre en disco: " & (I1 * I2 * I3) End Sub

    Crear un efecto Shade al estilo de los programas de instalacin:

    Crear un proyecto nuevo y escribir el cdigo siguiente:

    Private Sub Form_Resize() Form1.Cls Form1.AutoRedraw = True Form1.DrawStyle = 6 Form1.DrawMode = 13 Form1.DrawWidth = 2 Form1.ScaleMode = 3 Form1.ScaleHeight = (256 * 2) For i = 0 To 255 Form1.Line (0, Y)-(Form1.Width, Y + 2), RGB(0, 0, i), BF Y = Y + 2 Next i End Sub

    Situar el cursor encima de un determinado control (p. ej.: un botn):

    Escribir el cdigo siguiente en el mdulo:

    Declare Sub SetCursorPos Lib "User32" (ByVal X As Integer, ByVal Y As Integer)

    Insertar un botn en el formulario y escribir el siguiente cdigo:

    Private Sub Form_Load() X% = (Form1.Left + Command1.Left + Command1.Width / 2 + 60) / Screen.TwipsPerPixelX Y% = (Form1.Top + Command1.Top + Command1.Height / 2 + 360) / Screen.TwipsPerPixelY SetCursorPos X%, Y% End Sub

    Men PopUp en un TextBox:

    Ejemplo para no visualizar el men PopUp implcito de Windows:

    En el evento MouseDown del control TextBox escriba:

    Private Sub Editor1_MouseDown(Button As Integer, Shift As Integer, x As Single, Y As Single) If Button = 2 Then

  • Editor1.Enabled = False PopupMenu MiMenu Editor1.Enabled = True Editor1.SetFocus End If End Sub

    Hacer sonar un fichero Wav o Midi:

    Insertar el siguiente cdigo en un mdulo:

    Declare Function mciExecute Lib "winmm.dll" (ByVal lpstrCommand As String) As Long

    Insertar un botn en el formulario y escribir el siguiente cdigo:

    Private Sub Command1_Click() iResult = mciExecute("Play c:\windows\ringin.wav") End Sub

    Hacer un formulario flotante al estilo de Visual Basic:

    Crear un nuevo proyecto, insertar un botn al formulario que inserte un formulario ms y un mdulo. Pegue el siguiente cdigo en el mdulo:

    Declare Function SetParent Lib "user32" (ByVal hWndChild As Long, ByVal hWndNewParent As Long) As Long

    Peguar el siguiente cdigo en el formulario principal:

    Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer) Unload Form2 End Sub

    Private Sub Command1_Click() Dim ret As Integer If doshow = False Then ret = SetParent(Form2.hWnd, Form1.hWnd) Form2.Left = 0 Form2.Top = 0 Form2.Show doshow = True Else Form2.Hide doshow = False End If End Sub

  • Comprobar si el programa ya est en ejecucin:

    Crear un nuevo proyecto e insertar el siguiente cdigo:

    Private Sub Form_Load() If App.PrevInstance Then Msg = App.EXEName & ".EXE" & " ya est en ejecucin" MsgBox Msg, 16, "Aplicacin." End End If End Sub

    Hallar el nombre del PC en Windows 95 o Windows NT:

    Cree un nuevo proyecto e inserte dos ButtonClick y un Mdulo:

    Pegue el siguiente cdigo en el formulario:

    Private Sub Command1_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) Dim nPC as String Dim buffer As String Dim estado As Long buffer = String$(255, " ") estado = GetComputerName(buffer, 255) If estado 0 Then nPC = Left(buffer, 255) End If MsgBox "Nombre del PC: " & nPC End Sub

    Private Sub Command2_Click() Unload Form1 End Sub

    Pegue el siguiente cdigo en el mdulo:

    Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long

    Eliminar el sonido "Beep" cuando pulsamos Enter en un TextBox:

    Crear un nuevo proyecto e insertar un TextBox:

    Peguar el siguiente cdigo en el formulario:

    Private Sub Text1_KeyPress(KeyAscii As Integer)

  • If KeyAscii = 13 Or KeyAscii = 9 Then KeyAscii = 0 End Sub

    Ocultar y mostrar el puntero del ratn:

    Crear un nuevo proyecto e insertar dos ButtonClick y un Mdulo:

    Pegue el siguiente cdigo en el formulario:

    Private Sub Command1_Click() result = ShowCursor(False) End Sub

    Private Sub Command2_Click() result = ShowCursor(True) End Sub

    Usar las teclas alternativas Alt+O para ocultarlo y Alt+M para mostrarlo.

    Peguar el siguiente cdigo en el mdulo:

    Declare Function ShowCursor Lib "user32" (ByVal bShow As Long) As Long

    Calcular el nmero de serie de un disco:

    Crear un nuevo proyecto e insertar el siguiente cdigo en el formulario:

    Private Declare Function GetVolumeInformation& Lib "kernel32" Alias "GetVolumeInformationA" (ByVal lpRootPathName As String, ByVal pVolumeNameBuffer As String, ByVal nVolumeNameSize As Long, lpVolumeSerialNumber As Long, lpMaximumComponentLength As Long, lpFileSystemFlags As Long, ByVal lpFileSystemNameBuffer As String, ByVal nFileSystemNameSize As Long)

    Private Sub Form_Load() Dim cad1 As String * 256 Dim cad2 As String * 256 Dim numSerie As Long Dim longitud As Long Dim flag As Long unidad = "C:\" Call GetVolumeInformation(unidad, cad1, 256, numSerie, longitud, flag, cad2, 256) MsgBox "Numero de Serie de la unidad " & unidad & " = " & numSerie End Sub

    Trucos Breves 2

  • Seleccionar todo un procedimiento Para seleccionar un procedimiento completo (ya sea para borrarlo o para copiarlo a otro formulario) abrimos la pantalla de edicin correspondiente y luego hacemos un doble clic en la parte izquierda de la misma (donde el cursor cambia a una flecha apuntando hacia la derecha).

    Cambiar rpidamente la propiedad Enabled La propiedad Enabled de un objeto se puede alternar fcilmente con una nica lnea de cdigo: optAlternar.Enabled = NOT optAlternar.Enabled Este cdigo es independiente de la definicin de True y False, la cual vara segn la versin de VB utilizada. Ya sea que se represente numricamente (-1 = True; 0 = False) o lgicamente, la operacin NOT se adapta para dar el resultado correcto.

    Date y Date$ no son equivalentes La funcin Date$ devuelve la fecha del sistema en un string con el formato MM-DD-AAAA. Date devuelve un variant con el formato de fecha especificado en el Panel de Control (puede devolver, por ejemplo, DD-MM-AA). Si queremos realizar clculos con fechas, debemos utilizar Date$. Para mostrar la fecha actual al usuario, basta con usar Date (sin el smbolo $).

    "Couldn't find installable ISAM" En una aplicacin que accede a bases de datos, este error indica que VB no encuentra informacin sobre los archivos de acceso a bases de datos. Debemos crear un archivo en la carpeta de Windows con esa informacin: copiar el archivo Vb.INI a dicha subcarpeta, con el nombre de la aplicacin ejecutable y la extensin INI (por ejemplo, Agenda.INI).

    Evitar la carga de complementos Al cargar VB 4 o 5, cualquier complemento (Add-In) activo tambin se ejecuta. Si hay un error en algn complemento, puede ocurrir un GPF (falla de proteccin general). Para evitar esto, apagar los complementos antes de cargar VB, editando el archivo VBAddin.INI (en la carpeta de Windows), poniendo un 0 al lado de cada complemento. Por ejemplo: AppWizard.Wizard=0.

    Pasar cadenas de caracteres a una DLL VB presenta un problema a la hora de recibir cadenas de caracteres grandes de una DLL. Se produce una sobrecarga que demora el procesamiento, aun cuando ningn resultado es devuelto. Por esta razn, en programas de tiempo crtico es necesario salvar este inconveniente pasando cadenas inicializadas con la longitud exacta que se espera recibir.

  • Descargar formularios poco utilizados Hay que tener en cuenta que, aunque estn ocultos, los formularios ocupan un espacio de memoria. Tener en memoria un formulario con muchos controles que se usar una sola vez no resulta una muy buena idea, o sea que no es conveniente ocultarlo. En tal caso, conviene descargarlo despus de usado.

    Evitar el uso de las propiedades por defecto Si bien las propiedades por defecto muchas veces nos ahorran tipear unos cuantos caracteres dems, no siempre es bueno confiar en ellas. Por ejemplo, algunas propiedades por defecto cambiaron de Visual Basic 3 a la versin 4, causando "cuelgues" inexplicables. Aunque es un poco ms trabajoso, conviene utilizar todas las propiedades explcitamente.

    Comentar e indentar el cdigo Realizar comentarios acerca de cmo funciona una rutina, e indentar el cdigo de la misma para que sea ms fcil de leer, son dos acciones que debemos realizar siempre al programar. Un simple rengln aclaratorio puede ahorrar horas de prueba y error el da de maana. Indentar significa poner cada ciclo repetitivo hacia la derecha, para lo cual basta una presin de la tecla [TAB].

    Grabar antes de ejecutar Es una buena costumbre de programacin el grabar los programas antes de ejecutarlos. Esto es especialmente recomendado en el caso de usar alguna funcin API, puesto que una mala definicin de la misma, o el paso incorrecto de algn argumento, pueden causar un GPF (Error de proteccin general) en Visual Basic, e incluso en el mismo Windows.

    Seleccionar varios controles Para setear un grupo de propiedades en varios controles, podemos acelerar el trabajo seleccionndolos a todos y seteando las propiedades una sola vez. Para ello se "dibuja" un rectngulo que contenga a todos los controles a seleccionar. Automticamente, VB mostrar en la ventana de propiedades slo las que son comunes a todos los controles seleccionados, pudiendo setearlas en conjunto.

    Borrar las variables objeto Al terminar de usar una variable que contiene un objeto (por ejemplo, una variable definida As Database) conviene setear su valor a Nothing. Esto libera la memoria ocupada por dicha variable, lo que no siempre ocurre al cerrar el objeto. Por ejemplo: Dim DB As Database ' Abro la base Set DB = OpenDatabase ("C:\VB\BIBLIO.MDB") ...

    ' Cierro DB.Close

  • ' Libero la memoria Set DB = Nothing

    Evitar el "beep" del [ENTER] Muchas veces, cuando se ingresa informacin en una caja de texto y se presiona la tecla [ENTER], se escucha un "beep". Para evitar esto, colocar el cdigo siguiente en el evento KeyPress de la caja de texto: If KeyAscii = Asc(vbCR) Then

    KeyAscii = 0 End If

    TextBox de slo lectura Para hacer que un TextBox sea de slo lectura, podemos setear su propiedad Enabled a False. Sin embargo, esto le da un feo color gris que habitualmente dificulta. Otra manera de hacerlo, ms elegante, es incluir el siguiente cdigo en el evento KeyPress de dicho control (el cual no impide que el usuario coloque el cursor sobre l): KeyAscii = 0

    Error al utilizar SetFocus Si utilizamos el mtodo SetFocus sobre un control o formulario que no est visible o habilitado (propiedad Enabled), Visual Basic puede llegar a colgar nuestra aplicacin, si es que no se utiliza control de errores. Antes de usar este mtodo, hay que asegurarse que el control est visible y habilitado.

    La excepcin que confirma la regla Si bien el truco del SetFocus funciona casi siempre, hay una excepcin muy importante, constituida por los mtodos grficos (Print, Line, Circle y PSet). Al llamar a estos mtodos no puede usarse la estructura With ... End With, debindose anteponer el objeto a dichos mtodos, aun dentro de dicha estructura. Un ejemplo sera: With Picture

    .Move 0, 0

    Picture.Print "Hola, Mundo!" End UIT

    Evitar cadenas nulas en campos de Access Si se utiliza una base de datos de Access, los campos alfanumricos contienen valor NULL hasta tanto se les asigne algn valor (aunque sea una cadena vaca). Si se lee un campo con

  • valor NULL de un RecordSet, asignando su valor a una variable de tipo cadena, se produce un error de ejecucin. Para evitar esto, se concatena una cadena vaca a cada campo en cuanto se lo lee.

    Usar Sleep en lugar de DoEvents En un programa que se ejecuta en Windows 95 o Windows NT, es conveniente usar la funcin API Sleep. DoEvents pierde parte de su tiempo procesando mensajes del mismo proceso, lo que en un entorno multitarea es innecesario. La declaracin de la funcin es: Public Declare Sub Sleep Lib "KERNEL32" Alias Sleep (ByVal Milisegundos As Long) Y se usa de la siguiente manera: Sleep 0&

    Error al cambiar el tamao de los formularios Si intentamos cambiar el tamao de un formulario mientras est minimizado, obtendremos un error. Para evitar esto, ay que chequear antes todo el estado del formulario. Esto se logra con el siguiente fragmento de cdigo:

    If Me.WindowState 1 Then

    ' NO estoy minimizado ' El cdigo para mover o cambiar el tamao del formulario va aqui. End If

    No genera eventos al mostrar un MessageBox

    Mientras un programa se encuentra mostrando un cuadro de mensaje en la pantalla (generado con la instruccin MsgBox) no admite que se produzca ningn evento. Esto es para prevenir la ejecucin de cdigo que podra causar problemas, ya que un mensaje de este tipo slo debera aparecer en contadas ocasiones.

    Cantidad de Bytes que Ocupa un Directorio

    Sub Form_Load() Dim FileName As String Dim FileSize As Currency Dim Directory As String Directory = "c:\windows\" FileName = Dir$(Directory & "*.*") FileSize = 0

    Do While FileName "" FileSize = FileSize + FileLen(Directory & FileName) FileName = Dir$

  • Loop

    Text1.Text = "Este directorio ocupa la cantidad de bytes = " + Str$(FileSize) End Sub

    Entrar en las Propiedades de Accesibilidad 1. Crear un nuevo formulario, Form1 por defecto 2. Aadir un boton al formulario "Command Button control" 3. Aadir el siguiente codigo a la propieded Clik del boton.

    Private Sub Command1_Click() X = Shell("Rundll32.exe shell32.dll,Control_RunDLL main.cpl @2") End Sub

    Trucos Breves 3

    Como aumentar el Tamao de un RichTextBox en Ejecucin (y cualquier TextBox, Picture, etc.)

    Private Sub Form_Resize() If Not Me.WindowState = vbMinimized Then RichTextBox1.Move 0, 0, Me.Width - 100, Me.Height - 400 End If End Sub

    Despliegue Automtico de un ComboBox al recibir el Foco...

    En primer lugar, debes declarar la funcion en un modulo BAS: Declare Function SendMessage Lib "user32" Alias "SendMessageA" _ (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, _lParam As Long) As Long

    Y escribe este cdigo en el evento GotFocus del control ComboBox:

    Sub Combo1_GotFocus() Const CB_SHOWDROPDOWN = &H14F Dim Tmp Tmp = SendMessage(Combo1.hwnd, CB_SHOWDROPDOWN, 1, ByVal 0&) End Sub

    CheckBox en DBGrid...

    El Grid tiene una propiedad Columns que hace referencia a la columna encuestion. La columna tiene otro objeto ValueItems que determina el aspecto de la columna. La propiedad Presentation

  • de este objeto determina el modo de presentacin. El valor 4 representa a un checkbox.

    TDbGrid1.Columns(1).ValueItems.Presentation = 4

    Detectar si cambia el contenido de un Control TextBox

    Solamente necesitamos un control TextBox y declarar en un Modulo lo siguiente:

    Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, _ ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long

    (Ojo, toda esta declaracion debe estar en una sola linea!!)

    En el Evento Click del Form1 colocar lo siguiente:

    Sub Form_Click() If SendMessage(Text1.hWnd, &HB8, 0, ByVal 0&) = 1 then Form1.Caption = "Se ha cambiado el Texto" Else Form1.Caption = "Se ha dejado igual el Texto" End If End Sub

    Una ventana con forma ELIPTICA !!!???

    Solamente necesitamos declarar en un Modulo lo siguiente:

    Public Declare Function SetWindowRgn Lib "user32" Alias "SetWindowRgn" (ByVal hWnd As Long, _ ByVal hRgn As Long, ByVal bRedraw As Boolean) As Long Public Declare Function CreateEllipticRgn Lib "gdi32" Alias "CreateEllipticRgn" (ByVal X1 As Long, _ ByVal Y1 As Long, ByVal X2 As Long, ByVal Y2 As Long) As Long

    En el evento click de la ventana:

    Private Sub Form_Click() Dim Xs as Long, Ys as Long Xs = Me.Width / Screen.TwipsPerPixelX Ys = Me.Height / Screen.TwipsPerPixelY SetWindowRgn hWnd, CreateEllipticRng(0, 0, Xs, Ys), True End Sub

  • Utilizacin de los controles DirListBox, DriveListBox y FileListBox

    Para ver el funcionamiento de este pequeo visor de iconos necesitamos colocar en un Form1 (default) los siguientes controles:

    1 Control DriveListBox 1 Control DirListBox 1 Control FileListBox 1 Control Picture1 1 Label1

    El Codigo a colocar es el siguiente: Private Sub Dir1_Change() File1.Path = Dir1.Path End Sub Private Sub Drive1_Change() Dir1.Path = Drive1.Drive End Sub Private Sub File1_Click() Picture1.Picture = LoadPicture(Dir1.Path & "/" & File1.FileName) Label1.Caption = "Icono Seleccionado: " & UCase$(File1.FilaName) End Sub Private Sub File1_PathChange() File1.FileName = "*.ICO" End Sub

    El mtodo ARRANGE El mtodo ARRANGE se aplica (casi exclusivamente) en los formularios MDI, ya que es utilizado para ordenar de diversas formas los iconos y las ventanas abiertas. Este mtodo es el aplicado en un item de men que (habitualmente) llamamos Ventana, donde, por ejemplo colocaremos como sub-items lo siguiente: Cascada, Mosaico Vertical, Mosaico Horizontal y Organizar Iconos. El cdigo para la ejecucin se coloca en los eventos CLICK de cada item. Ejemplo: Private Sub Organizar_Iconos_Click() MDIForm.Arrange 3 End Sub Private Sub Mosaico_Vertical_Click() MDIForm.Arrange 2 End Sub Private Sub Mosaico_Horizontal_Click() MDIForm.Arrange 1 End Sub Private Sub Cascada_Click() MDIForm.Arrange 0 End Sub

    Un sencillo Cronmetro Para ejecutar un lapso de tiempo x (por ejemplo 5 segundos), escribir el siguiente codigo en un Modulo Nuevo: Public Sub Esperar(Tiempo as Single) Dim ComienzoTiempo as Single

  • Dim FinTiempo as Single ComienzoTiempo = Timer FinTiempo = ComienzoTiempo + Tiempo Do While FinTiempo > Timer Do Events If ComienzoTiempo > Timer Then FinTiempo = FinTiempo - 24 * 60 * 60 End If Loop End Sub Para "llamarlo" desde un Form comun, colocar (por ejemplo, en el evento Click) Esperar(5)

    Eliminar el "Beep" al pasar el foco de un TextBox a otro control... Insertar el siguiente Codigo en el evento KeyPress de un TextBox de nuestro Formulario: Private Sub Text1_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Or KeyAscii = 9 Then KeyAscii = 0 End Sub

    Situar el Cursor en un Control determinado Para situar el cursor encima de un control determinado, por ejemplo un Botn, situar el siguiente codigo en un Modulo: Declare sub SetCursorPos Lib "User32" (ByVal X as Integer, ByVal Y as Integer) Insertar en siguiente cdigo en el evento Load de el Form: Private Sub Form1_Load() X % = (Form1.Left + Command1.Left + Command1.Width / 2 + 60 ) / Screen.Twips Y% = (Form1.Top + Command1.Top + Command1.Height / 2 + 360) / Screen.Twips SetCursorPos X%, Y% End Sub Nota: Para que sea mas fcil la escritura del codigo a colocar en el modulo, Visual Basic trae el Visor de API de Windows

    Mostrar / Ocultar el puntero del Mouse Insertar el siguiente Codigo en los eventos Click de dos botones en nuestro Form Private Declare Function ShowCursor Lib "user32" (ByVal bShow As Long) As Long Private Sub cmdOcultar_Click() resultado = ShowCursor(False) End Sub Private Sub cmbMostrar_Click() resultado = ShowCursor(True) End Sub

    Pasar de un control a otro con "Enter" Cambiar la Propiedad KeyPreview del control TextBox a True e inserte el siguiente Codigo en el evento KeyPress del Form: Private Declare Sub Form1_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then SendKeys "{tab}" KeyAscii = 0

  • End If End Sub

    Provocar la Transparencia de un Form Insertar el siguiente Codigo en un Modulo: Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long Nota: Debe estar todo en una sola linea (Usar el Visor de Texto API, que viene con Visual Basic) Insertar el siguiente Codigo en CommandButton para probar: Private Sub Command1_Click() Dim Resp As Long Resp = SetWindowLong(Me.hWnd, -20, &H20&) Form1.Refresh End Sub Arreglo sugerido por Esteban: En un mdulo: Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long Public Const WS_EX_TRANSPARENT = &H20& Public Const GWL_HINSTANCE = (-6) Public Const GWL_EXSTYLE = (-20) Public Const GWL_HWNDPARENT = (-8) Public Const GWL_ID = (-12) Public Const GWL_STYLE = (-16) Public Const GWL_USERDATA = (-21) Public Const GWL_WNDPROC = (-4) y en el Form_Load Call SetWindowLong(Form1.hwnd, GWL_EXSTYLE, WS_EX_TRANSPARENT) Gracias, Esteban!

    Centrar una Ventana Para Centrar una ventana en el medio de la pantalla, colocar el siguiente codigo en el evento Load de un Form: Me.Move (Sreen.Width - Me.Width) / 2, Me.Move (Screen.Height - Me.Height) / 2

    Presentar una pantalla Acerca de... por defecto (1): Private Declare Function ShellAbout Lib "shell32.dll" Alias _ "ShellAboutA" (ByVal hwnd As Long, ByVal szApp As String, _ ByVal szOtherStuff As String, ByVal hIcon As Long) As Long Private Sub Command1_Click() Call ShellAbout(Me.hwnd, "Mi Programa", "Copyright 1999, PMMF", Me.Icon) End Sub

    Utilizando el Control Graph Primero rellenas las etiquetas del graph, es decir, lo que es la "leyenda", y pones a 0 los datos del Graph (de paso) ' Muchos cajeros, un slo dato. grafico_frm.grafico.ColumnCount = (Len(x2) - 1) / 3 ReDim label_y(1 To grafico_frm.grafico.ColumnCount) ' Toma nota de las etiquetas (y) i = 1

  • For i1 = 0 To lista_cajeros.ListCount - 1 If lista_cajeros.Selected(i1) Then label_y(i) = lista_cajeros.List(i1) ' Nombre de las leyendas grafico_frm.grafico.Column = i grafico_frm.grafico.ColumnLabel = label_y(i) i = i + 1 If i = (grafico_frm.grafico.ColumnCount + 1) Then Exit For End If End If Next i1 For i1 = 0 To lista_datos.ListCount - 1 If lista_datos.Selected(i1) Then x = "'" + lista_datos.List(i1) + "'" Exit For End If Next i1 ' Despus, rellenas los datos. For i1 = 1 To grafico_frm.grafico.RowCount For i2 = 1 To grafico_frm.grafico.ColumnCount grafico_frm.grafico.Row = i1 grafico_frm.grafico.Column = i2 grid.row=i1 grid.col=i2 grafico_frm.grafico.Data = val(grid.text) Next i2 Next i1 (Esperemos que este ejemplo funcione, jeje)

    Imprimir el Grafico Resultante del Ejemplo Anterior (Con el Control GRAPH) Printer.PaintPicture picture1.picture, PosicionVertical, PosicionHorizontal Printer.EndDoc 'Envia los datos a la impresora

    Enviar Faxes Utilizando los controles de VB Utilizaremos para ello los controles MAPI Messages y MAPI Session para crear un mensaje de Exchange. Si en el campo de la direccin e-mail empiezas por "Fax: " y continuas con el n de fax, conseguirs enviar el mensaje a travs del servicio MS Fax. Ten cuidado de utilizar un perfil de Exchange que solo incluya el servicio Fax, no el Internet Mail, porque si no intentar enviarlo por los dos sistemas. MAPISession1.LogonUI = False wPerfil = "Configuraciones de MS Exchange" MAPISession1.UserName = wPerfil MAPISession1.SignOn MAPIMessages1.SessionID = MAPISession1.SessionID Sesion = True lblEstado = "Creando mensaje..." MAPIMessages1.ComposeMAPIMessages1.MsgSubject = "" ' No utilizar el campo de texto. Lo intenta imprimir con el Word como ' segunda hoja y falla dando error WordBasic n 124 (teniendo instalado el Parche) MAPIMessages1.MsgNoteText = "Este es el texto de la prueba....." MAPIMessages1.RecipIndex = 0 MAPIMessages1.RecipIndex = NumDestino

  • MAPIMessages1.RecipType = mapToList MAPIMessages1.RecipDisplayName = Data1.Recordset.Fields(1) MAPIMessages1.RecipAddress = "Fax:" & Data1.Recordset.Fields(0) MAPIMessages1.AttachmentIndex = I MAPIMessages1.AttachmentPosition = I MAPIMessages1.AttachmentPathName = wPath MAPIMessages1.AttachmentName = wName lblEstado = "Enviando mensaje..." MAPIMessages1.Send MAPISession1.SignOff

    Un Reporte de CrystalReport en una Ventana?? Dim Frm As Form Set Frm = New Form1 CrystalReport1.Destination = crptToWindow CrystalReport1.WindowParentHandle = Form1.hwnd CrystalReport1.Action = 1Siendo el Form1 MDI.

    El uso del Menu Edicion en tiempo de Ejecucion En un Modulo aparte (o bien dentro de las declaraciones Generales del Form donde vamos a invocarlo) Declare Function GetActiveWindow Lib "user32" Alias "GetActiveWindow" () As Long Luego esta porcion de codigo la colocamos en el MDIForm (donde tenemos el Menu Edicion... por ejemplo) ' en el caso de que tenga 2 formularios ' como se cual estoy ocupando ? ' .... de esta manera: ' reviso el primer formulario If Form1.hWnd = GetActiveWindow Then .... ' hace esto End If ' reviso el segundo formulario If form2.hWnd = GetActiveWindow Then .... ' hace esto otro End If

    Encriptacion XOR

    El operador lgico XOR suministra un interesante algoritmo de encriptacin, se codifica en la primera llamada y se decodifica en la segunda. Ejemplo:

    Private Sub Form_Load() Dim s As String s = "Hola!" '//Codifica XORStringEncrypt s, "MiClave" Show Print "Codificado: "; s '//Decodifica XORStringEncrypt s, "MiClave" Print "Decodificado: "; s End Sub

  • Private Sub XORStringEncrypt(s As String, PassWord As String) Dim n As Long Dim i As Long Dim Char As Long n = Len(PassWord) For i = 1 To Len(s) Char = Asc(Mid$(PassWord, (i Mod n) - n * ((i Mod n) = 0), 1)) Mid$(s, i, 1) = Chr$(Asc(Mid$(s, i, 1)) Xor Char) Next End Sub

    Leer una Cadena (string) dentro de otra... En particular existen muchos comando tales conmo: CommandString="Source=File.txt;Path=C:\CommonFiles;Title=;..."

    Resulta que deseamos obtener lo que corresponde a Path= de la cadena anterior. La siguiente funcin se usa de esta manera: s = GetSubString(CommandString, "Path=", ";")

    Public Function GetSubString( _ s As String, _ StartDelim As String, _ EndDelim As String _ ) As String Dim nStartDelim As Long Dim nEndDelim As Long nStartDelim = InStr(s, StartDelim) If nStartDelim Then nStartDelim = nStartDelim + Len(StartDelim) nEndDelim = InStr(nStartDelim, s, EndDelim) If nEndDelim Then GetSubString = Mid$(s, nStartDelim, nEndDelim - nStartDelim) End If End If End Function En el siguiente ejemplo, obtengo el nombre de la base de datos de un DataEnvirnment

    Dim DE As New dePPDMMirror gsDatabaseConnection = DE.cnnPPDMMirror.ConnectionString gsDatabaseName = GetSubString(gsDatabaseConnection, "Source=", ";") Set DE = Nothing

  • Fecha aleatoria

    A veces es til, generalmente para pruebas, generar una fecha aleatoria dentro de un rango, p.e deseo una fecha entre el 1/1/1960 y 1/1/2000, llamariamos a esta funcin como MyDate=GetRandomDate("1/1/1960", "1/1/2000")

    Private Function GetRandomDate(ByVal StartDate As Date, ByVal EndDate As Date) As Date Static AnotherCall As Boolean Dim nDays As Single On Error GoTo ErrorHandler If Not AnotherCall Then Randomize Timer AnotherCall = True End If nDays = DateValue(EndDate) - DateValue(StartDate) GetRandomDate = CDate(DateValue(StartDate) + nDays * Rnd()) Exit Function ErrorHandler: GetRandomDate = Null End Function

    Generar un nombre de archivo aleatorio

    La siguiente funcin genera un nombre de archivo aleatorio. Puede ser utile cuando se requieren archivos temporales.

    Private Function GenerateRandomFileName() As String Const MASKNUM As String = "_0123456789" Const MASKCHR As String = "abcdefghijklmnoprstuvwxyz" Const MASK As String = MASKCHR + MASKNUM Const MINLEN As Integer = 4 Const MAXLEN As Integer = 12 Dim nMask As Long Dim nFile As Long Dim sFile As String Dim sExt As String Dim i As Long Dim nChr As Long nFile = MINLEN + (MAXLEN - MINLEN) * Rnd() nMask = Len(MASK) For i = 1 To nFile nChr = Int(nMask * Rnd()) + 1 sFile = sFile + Mid$(MASK, nChr, 1)

  • Next nMask = Len(MASKCHR) For i = 1 To 3 nChr = Int(nMask * Rnd()) + 1 sExt = sExt + Mid$(MASKCHR, nChr, 1) Next GenerateRandomFileName = sFile + "." + sExt End Function

    NOTAS 1) La funcin asume que la semilla de aleatorios fue iniciada previamente (para ms informacion, ver "Randomize") 2) Puede obtener el nombre del archivo de temporales de Windows de la siguiente expresin: TempPath = Environ("TEMP") & "\"

    Trasnformar una Hora a Decimal (y viceversa...)

    En algunos clculos es requerido transformar datos de hora a decimal y viceversa (en Topografa es til). P.e. la hora 10:30 AM ser 10.5 en decimal.

    Public Function HourDec(h As Variant) As Variant If Not IsNull(h) Then HourDec = Hour(h) + Minute(h) / 60 + Second(h) / 3600 End If End Function Public Function DecHour(h As Variant) As Variant Dim nHour As Integer Dim nMinutes As Integer Dim nSeconds As Integer nHour = Int(h) nMinutes = Int((h - nHour) * 60) nSeconds = Int(((h - nHour) * 60 - nMinutes) * 60) DecHour = nHour & ":" & nMinutes & ":" & nSeconds End Function

    Ejemplo:

    Private Sub Command1_Click() Dim h As Single Dim d As String Cls d = "10:37:58" h = HourDec(d) Print "Hora Decimal = "; d Print "Hora Estndar = "; h

  • Print "Hora de Decimal a Estndar = "; DecHour(h) End Sub

    El parmetro de HourDec puede ser un dato Date, expresin que retorne Date (por ejemplo la funcin Now), o una cadena, "hh:mm:ss" como en ejemplo.

    Incremento continuo

    Desafortunadamente Visual Basic no tiene operador de incrementacin continua, es decir el famoso i++ del lenguaje C. Podamos simular algo parecido:

    Public Static Function Plus(Optional Start As Variant) As Long Dim i As Long If Not IsMissing(Start) Then i = Start-1 End If i = i + 1 Plus = i End Function

    Esta pequea funcin puede ser extremadamente til en cdigo para obtener recursos, digamos que es comn:

    Dim I As Long I=100 Caption = LoadResString(I) lblPINCode = LoadResString(1 + I) fraAccount = LoadResString(2 + I) optChecking.Caption = LoadResString(3 + I) optSavings.Caption = LoadResString(4 + I) ... cmdOK.Caption = LoadResString(n + I)

    Supongamos que hacemos un cambio en el archivo recursos : lblPINCode ya no se usa en el formulario, y compilamos el recurso. Para actualizar el cdigo tendremos que ir lnea por lnea para actualizar el I + x. - Nada prctico. Mientras que si escribimos:

    Caption = LoadResString(Plus(100)) lblPINCode = LoadResString(Plus) fraAccount = LoadResString(Plus) optChecking.Caption = LoadResString(Plus) optSavings.Caption = LoadResString(Plus) ... cmdOK.Caption = LoadResString(Plus)

    La actualizacin mensionada consistir solo en eliminar la lnea: lblPINCode = LoadResString(PlusI). Mejor imposible

  • Crear Cadenas Multineas de manera practica

    Pienso que todos nos hemos hartado de escribir s = s + "algo"& vbCrLf & _ ... etc. La siguiente funcin es una alternativa simple de crear cadenas multiline:

    Public Function StrChain(ParamArray v() As Variant) As String Dim i As Integer Dim n As Integer Dim rtn As String n = UBound(v) For i = 0 To n rtn = rtn & v(i) If i < n Then rtn = rtn & vbCrLf End If Next StrChain = rtn End Function

    P.e:

    Text1 = StrChain( _ "Hola", _ "cmo", _ "estas")

    O simplemente Text1 = StrChain( "Hola", "cmo", "estas"), es ms cmodo que:

    Text1 = "Hola"& vbCrLf & "cmo" & VbCrLf & "estas"

    Claro, suponiendo que las cadenas concatenadas sean extensas, como un SQL o un comando Script.

    Saber si un archivo es binario o solo texto

    Algunos archivos tienen extensiones personalizadas y algunas veces debemos evaluar si son o no binarios antes de procesarlos.

    Public Function IsBinaryFile(File As String) As Boolean Const aLf = 10, aCR = 13, aSP = 32 Const MaxRead = 2 ^ 15 - 1 Dim ff As Integer Dim s As Integer Dim i As Integer

  • Dim n As Integer Dim Rtn As Boolean On Error GoTo IsBinaryFile_Err ff = FreeFile Open File For Binary Access Read As #ff n = IIf(LOF(ff) > MaxRead, MaxRead - 1, LOF(ff)) Do i = i + 1 If i >= n Then IsBinaryFile = False Rtn = True Else s = Asc(Input$(1, #ff)) If s >= aSP Then Else If s = aCR Or s = aLf Then Else IsBinaryFile = True Rtn = True End If End If End If Loop Until Rtn Close ff Exit Function IsBinaryFile_Err: If ff Then Close ff MsgBox "Error verifying file " & File & vbCrLf & Err.Description End Function

    Simplemente pase el nombre del archivo al argumento y la funcin retornata un valor bolean. Por ejemplo MsgBox " Es binario Command.Com ? ... " & IsBinaryFile("command.com").

    Estimar el tiempo de proceso

    Esta es una vieja tcnica que emplean para estimar la duracin de un bloque de cdigo o proceso. Es til para comparar el tiempo de dos o ms algoritmos diferentes que resuelven un mismo problema.

    Dim t As Single DoEvents t = Timer '// Proceso ... MsgBox "Elapse time = " & Format(Timer - t, "0.00")

  • Se redondea a dos decimales porque las milsimas de segundo son insignificantes. Debiera ejecutarse dos o tres veces para un estimado ms preciso. Por supuesto, existen tcnicas ms precisas para evaluacin de tiempos, pero esta suele ser aceptable.

    Como saber si mi form esta abierto...

    El procedimiento IsLoadForm retorna un bolean que indica si el formulario solicitado por su nombre se encuentra abierto. Opcionalmente se puede hacer activo si se encuentra en memoria. La funcin es til en interfaces MDI.

    Public Function IsLoadForm(ByVal FormCaption As String, Optional Active As Variant) As Boolean Dim rtn As Integer, i As Integer rtn = False Name = LCase(FormCaption) Do Until i > Forms.Count - 1 Or rtn If LCase(Forms(i).Caption) = FormCaption Then rtn = True i = i + 1 Loop If rtn Then If Not IsMissing(Active) Then If Active Then Forms(i - 1).WindowState = vbNormal End If End If End If IsLoadForm = rtn End Function

    Mostrar el contenido de un TextBox a medida que vamos escribiendo...

    En programas que ejecutan una tarea larga, me gusta agregar un texto de informacin al usuario a medida que las tareas se van ejecutando (al etilo de Autocad). La sigueinte tcnica fuerza que el texto se muestre continuamente. Use un TextBox Multiline con barras Scroll y nombre txtReport.

    '//API - en un modulo aparte... Private Declare Function SendMessageByVal Lib "user32" Alias "SendMessageA" ( _ ByVal hWnd As Long, _ ByVal wMsg As Long, _ ByVal wParam As Long, _ ByVal lParam As Long _ ) As Long Private Const EM_LINESCROLL As Long = &HB6 Private Const EM_GETLINECOUNT As Long = &HBA Private Sub Echo(Optional s As String = "")

  • Static n As Long On Error Resume Next With txtReport If Len(.Text) Then .Text = .Text & vbCrLf .Text = .Text & s '//To end of line (with API) n = SendMessageByVal(.hWnd, EM_GETLINECOUNT, 0, 0) SendMessageByVal .hWnd, EM_LINESCROLL, 0, n DoEvents End With End Sub

    NOTAS 1. Podra usar la lnea SendKeys "^{END}", True pero produce un efecto colateral en Windows98 (la barra de las ventana pierde su color) 2. Si desea situar el cursor al final del texto use: txtReport.SelStart = Len(txtReport.Text)

    Como contar los caracteres de una cadena...

    Option Explicit Function Cuantos(Inicio, Cadena As String, Caracter As String) Dim Resultado, sCuantos sCuantos = 0 'Inicializa la suma 'evita que entre si no hay nada que buscar If IsNull(Cadena) Or IsNull(Caracter) Or Len(Cadena) = 0 Or Len(Caracter)= 0 Then Exit Function Resultado = InStr(Inicio, Cadena, Caracter) 'localiza la 1 coincidencia Do While Resultado > 0 'y cuenta hasta que termina sCuantos = sCuantos + 1 Inicio = Resultado + 1 Resultado = InStr(Inicio, Cadena, Caracter) Loop Cuantos = sCuantos End Function

    Obligar a introducir solamente nmeros (I)

    Private Sub txtText1_KeyPress(KeyAscii As Integer) 'solo admitir dgitos, el punto y la coma 'si se pulsa alguna otra tecla, anular la pulsacin de teclado If InStr("0123456789.,", Chr(KeyAscii)) = 0 Then KeyAscii = 0

  • End If End Sub

    Sub Text1_Keypress(KeyAscii As Integer) If KeyAscii Asc("9") Then 'KeyAscii = 8 es el retroceso o BackSpace If KeyAscii 8 Then KeyAscii = 0 End If End If End Sub

    Obligar a introducir solamente nmeros (II)

    Private Sub txtText1_LostFocus() If IsNumeric(txtText1) = False then MsgBox "Lo siento. Debe Ingresar SOLAMENTE Nmeros.",vbInformation,"Cuidado!" txtText1.SetFocus End If

    Convertir nmeros en texto Esta funcin, convierte un nmero en su correspondiente trascripcin a letras. Funciona bien con nmeros enteros y con hasta 2 decimales, pero ms de 2 decimales se pierde y no "sabe" lo que dice. Debes introducir este cdigo en un mdulo (por ejemplo) y realizar la llamada con el nmero que deseas convertir. Por Ejemplo: Label1 = Numlet(CCur(Text1)) Option Explicit Dim Unidades$(9), Decenas$(9), Oncenas$(9) Dim Veintes$(9), Centenas$(9) Function Numlet$(NUM#) Dim DEC$, MILM$, MILL$, MILE$, UNID$ ReDim SALI$(11) Dim var$, I%, AUX$ 'NUM# = Round(NUM#, 2) var$ = Trim$(Str$(NUM#)) If InStr(var$, ".") = 0 Then var$ = var$ + ".00" End If If InStr(var$, ".") = Len(var$) - 1 Then var$ = var$ + "0" End If

  • var$ = String$(15 - Len(LTrim$(var$)), "0") + LTrim$(var$) DEC$ = Mid$(var$, 14, 2) MILM$ = Mid$(var$, 1, 3) MILL$ = Mid$(var$, 4, 3) MILE$ = Mid$(var$, 7, 3) UNID$ = Mid$(var$, 10, 3) For I% = 1 To 11: SALI$(I%) = " ": Next I% I% = 0 Unidades$(1) = "UNA " Unidades$(2) = "DOS " Unidades$(3) = "TRES " Unidades$(4) = "CUATRO " Unidades$(5) = "CINCO " Unidades$(6) = "SEIS " Unidades$(7) = "SIETE " Unidades$(8) = "OCHO " Unidades$(9) = "NUEVE " Decenas$(1) = "DIEZ " Decenas$(2) = "VEINTE " Decenas$(3) = "TREINTA " Decenas$(4) = "CUARENTA " Decenas$(5) = "CINCUENTA " Decenas$(6) = "SESENTA " Decenas$(7) = "SETENTA " Decenas$(8) = "OCHENTA " Decenas$(9) = "NOVENTA " Oncenas$(1) = "ONCE " Oncenas$(2) = "DOCE " Oncenas$(3) = "TRECE " Oncenas$(4) = "CATORCE " Oncenas$(5) = "QUINCE " Oncenas$(6) = "DIECISEIS " Oncenas$(7) = "DIECISIETE " Oncenas$(8) = "DIECIOCHO " Oncenas$(9) = "DIECINUEVE " Veintes$(1) = "VEINTIUNA " Veintes$(2) = "VEINTIDOS " Veintes$(3) = "VEINTITRES " Veintes$(4) = "VEINTICUATRO " Veintes$(5) = "VEINTICINCO " Veintes$(6) = "VEINTISEIS " Veintes$(7) = "VEINTISIETE " Veintes$(8) = "VEINTIOCHO " Veintes$(9) = "VEINTINUEVE " Centenas$(1) = " CIENTO " Centenas$(2) = " DOSCIENTOS " Centenas$(3) = " TRESCIENTOS " Centenas$(4) = "CUATROCIENTOS " Centenas$(5) = " QUINIENTOS "

  • Centenas$(6) = " SEISCIENTOS " Centenas$(7) = " SETECIENTOS " Centenas$(8) = " OCHOCIENTOS " Centenas$(9) = " NOVECIENTOS " If NUM# > 999999999999.99 Then Numlet$ = " ": Exit Function If Val(MILM$) >= 1 Then SALI$(2) = " MIL ": '** MILES DE MILLONES SALI$(4) = " MILLONES " If Val(MILM$) 1 Then Unidades$(1) = "UN " Veintes$(1) = "VEINTIUN " SALI$(1) = Descifrar$(Val(MILM$)) End If End If If Val(MILL$) >= 1 Then If Val(MILL$) < 2 Then SALI$(3) = "UN ": '*** UN MILLON If Trim$(SALI$(4)) "MILLONES" Then SALI$(4) = " MILLON " End If Else SALI$(4) = " MILLONES ": '*** VARIOS MILLONES Unidades$(1) = "UN " Veintes$(1) = "VEINTIUN " SALI$(3) = Descifrar$(Val(MILL$)) End If End If

    For I% = 2 To 9 Centenas$(I%) = Mid$(Centenas(I%), 1, 11) + "AS" Next I% If Val(MILE$) > 0 Then SALI$(6) = " MIL ": '*** MILES If Val(MILE$) 1 Then SALI$(5) = Descifrar$(Val(MILE$)) End If End If Unidades$(1) = "UNA " Veintes$(1) = "VEINTIUNA" If Val(UNID$) >= 1 Then SALI$(7) = Descifrar$(Val(UNID$)): '*** CIENTOS If Val(DEC$) >= 10 Then SALI$(8) = " CON ": '*** DECIMALES SALI$(10) = Descifrar$(Val(DEC$)) End If End If If Val(MILM$) = 0 And Val(MILL$) = 0 And Val(MILE$) = 0 And Val(UNID$) = 0 Then SALI$(7) = " CERO " AUX$ = "" For I% = 1 To 11 AUX$ = AUX$ + SALI$(I%) Next I%

  • Numlet$ = Trim$(AUX$) End Function Function Descifrar$(numero%) Static SAL$(4) Dim I%, CT As Double, DC As Double, DU As Double, UD As Double Dim VARIABLE$ For I% = 1 To 4: SAL$(I%) = " ": Next I% VARIABLE$ = String$(3 - Len(Trim$(Str$(numero%))), "0") + Trim$(Str$(numero%)) CT = Val(Mid$(VARIABLE$, 1, 1)): '*** CENTENA DC = Val(Mid$(VARIABLE$, 2, 1)): '*** DECENA DU = Val(Mid$(VARIABLE$, 2, 2)): '*** DECENA + UNIDAD UD = Val(Mid$(VARIABLE$, 3, 1)): '*** UNIDAD If numero% = 100 Then SAL$(1) = "CIEN " Else If CT 0 Then SAL$(1) = Centenas$(CT) If DC 0 Then If DU 10 And DU 20 Then If DC = 1 Then SAL$(2) = Oncenas$(UD): Descifrar$ = Trim$(SAL$(1) + " " + SAL$(2)) then Exit Function If DC = 2 Then SAL$(2) = Veintes$(UD): Descifrar$ = Trim$(SAL$(1) + " " + SAL$(2)) then Exit Function End If SAL$(2) = " " + Decenas$(DC) If UD 0 Then SAL$(3) = "Y " End If If UD 0 Then SAL$(4) = Unidades$(UD) End If Descifrar = Trim$(SAL$(1) + SAL$(2) + SAL$(3) + SAL$(4)) End Function

    Convertir nmeros romanos a rabes (no est probado) Es muy fcil de utilizar, le pasas la cadena con el nmero en rabe y te devuelve el nmero, necesitas las dos funciones que tienes a continuacin. Function ConvertirArabe(Romano As String) As Integer Dim Numero As Integer, Valor1 As Integer, Valor2 As Integer, Cadena As String If Len(Romano) = 0 Then ConvertirArabe = 0: Exit Function Cadena = Trim(Romano) Numero = 0 Do Valor1 = VerValor(left(Cadena, 1)) Cadena = Right$(Cadena, Len(Cadena) - 1) Valor2 = VerValor(left(Cadena, 1)) If Valor1 >= Valor2 Then Numero = Numero + Valor1

  • Else Numero = Numero - Valor1 End If Loop Until Len(Cadena) = 0 ConvertirArabe = Numero End Function Function VerValor(Simbolo As String) As Integer Select Case Simbolo Case "I" VerValor = 1 Case "V" VerValor = 5 Case "X" VerValor = 10 Case "L" VerValor = 50 Case "C" VerValor = 100 Case "D" VerValor = 500 Case "M" VerValor = 1000 Case "Q" VerValor = 5000 Case "H" VerValor = 10000 End Select End Function

    Convertir nmeros romanos a rabes -2- (no est probado) Function Num2Roman(ByVal N As Integer) As String Const Digits = "IVXLCDM" Dim i As Integer, Digit As Integer, Temp As String i = 1 Temp = "" Do While N > 0 Digit = N Mod 10 N = N \ 10 Select Case Digit Case 1 Temp = Mid(Digits, i, 1) & Temp Case 2 Temp = Mid(Digits, i, 1) & Mid(Digits, i, 1) & Temp Case 3 Temp = Mid(Digits, i, 1) & Mid(Digits, i, 1) & Mid(Digits, i, 1) & Temp Case 4 Temp = Mid(Digits, i, 2) & Temp Case 5 Temp = Mid(Digits, i + 1, 1) & Temp

  • Case 6 Temp = Mid(Digits, i + 1, 1) & Mid(Digits, i, 1) & Temp Case 7 Temp = Mid(Digits, i + 1, 1) & Mid(Digits, i, 1) & Mid(Digits, i, 1) & Temp Case 8 Temp = Mid(Digits, i + 1, 1) & Mid(Digits, i, 1) & Mid(Digits, i, 1) & Mid(Digits, i, 1) & Temp Case 9 Temp = Mid(Digits, i, 1) & Mid(Digits, i + 2, 1) & Temp End Select i = i + 2 Loop Num2Roman = Temp End Function

    Seleccionar todo el Texto al recibir el Foco

    Insertar el siguiente Codigo en el evento GotFocus de un TextBox:

    Private Sub Text1_GotFocus() Text1.SelStart = 0 Text1.SelLenght = Len(Text1.Text) End Sub

    Convertir a Maysculas/Minsculas segun vamos escribiendo

    Insertar el siguiente Codigo en el evento Change de un control TextBox

    Private Sub Text1_Change() Dim I as Integer Text1.Text = UCase(Text1.Text) I = Len(Text1.Text) Text1.SelStart(I) End Sub

    Nota: Si queremos convertir a minusculas, solo hay que cambiar UCase por LCase. Este codigo convierte a mayusculas/minusculas segun vamos escribiendo.-

    Validar Fechas

    Sub ValidarFecha(Fecha As String, valida As Boolean)

    Dim cadena As Date On Error GoTo error cadena = Format(Fecha, "dd/mm/yyyy")

  • If Not IsDate(cadena) Then MsgBox "Compruebe que ha introducido bien la fecha.", vbInformation Exit Sub End If If cadena > Date Then valida = True GoTo error Else valida = False End If Exit Sub error: MsgBox "La fecha no puede ser posterior a la fecha de hoy.", vbInformation, "Fecha invlida" valida = True Exit Sub End Sub

    Pasar de Decimal a Binario

    Function DecimalABinario(ByVal valor As Long) As String ' Declaracin de variables privadas a la funcin Dim mayor As Integer Dim retorno As String Dim a As Integer ' Localizamos el mayor exponente mayor = 0 Do While True If 2 ^ mayor > valor Then If mayor > 0 Then mayor = mayor - 1 End If Exit Do End If mayor = mayor + 1 Loop ' Calculamos el valor binario retorno = "" For a = mayor To 0 Step -1 If valor < (2 ^ a) Then retorno = retorno & "0" Else retorno = retorno & "1" valor = valor - (2 ^ a) End If Next a DecimalABinario = retorno End Function

  • Verificar si una Ventana "X" est cargada

    Private Declare Function FindWindow Lib "USER32" Alias "FindWindowA" ( _ ByVal lpszClassName As String, ByVal lpszWindow As String) As Long

    Llamaremos la funcin con un:

    If FindWindow(vbNullString, Caption) Then '//Esta abierta ventana con titulo Caption End If Sirve para ventanas dentro y fuera de la aplicacin, es decir, la usaremos para verificar si un formulario ya a sido cargado o para saber si CALC.EXE esta abierto. Como un detalle, vbNullString es lo que en C se conoce como un puntero nulo, estrictamente el parmetro es la clase de la ventana. Tambin puede ser de utilidad saber que FindWindow retorna el manejador hWnd si la ventana esta abierta.

    Inhabilitar por un ratito los botones de la barra Inicio: Los eventos Resize suelen tener ejecucin asncrona. Cuando un formulario utiliza controles ActiveX complejos (lase acceso a datos) que toman acciones de redimensionamiento, pueden fallar si el usuario, por ejemplo, maximiza la ventana antes de que termine de cargarse el formulario, o situaciones similares. La siguiente tcnica permite evitar este efecto.

    '//Protect while loading Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long) As Long Private Const GWL_STYLE = (-16) Private Const WS_SYSMENU = &H80000 Public Sub EnabledToolBoxMenu(frm As Form, Action As Boolean) Static rtn, rtnI If Action Then If rtnI Then rtn = SetWindowLong(frm.hwnd, GWL_STYLE, rtnI) End If Else rtnI = GetWindowLong(frm.hwnd, GWL_STYLE) rtn = rtnI And Not (WS_SYSMENU) rtn = SetWindowLong(frm.hwnd, GWL_STYLE, rtn) End If End Sub

  • La forma correcta de usar el procedimiento es la siguiente:

    Private Loading

    Private Sub Form_Load() Loading=True '//Cdigo de carga... Loading=False EnabledToolBoxMenu Me, True End Sub

    Private Sub Form_Activate() If Loading Then EnabledToolBoxMenu Me, False End If End Sub

    NOTA. Se pueden inhabilitar / habilitar separadamente los btones. API suministra otras constantes similares a WS_SYSMENU. Ver documentacin de SetWindowLong.

    Ocultar el Puntero del Mouse Para este ejemplo agregue un Timer a un formulario y fije la propiedad Interval a 3000. Cada 3 segundos se ocultar el Mouse. Private Declare Function ShowCursor Lib "user32" (ByVal bShow As Long) As Long Private Sub Timer1_Timer() Static HideMouse As Boolean HideMouse = Not HideMouse ShowCursor HideMouse End Sub NOTA. No esta garantizado que ShowCursor produzca el efecto deseado.

    Ejecutar un programa DOS desde VB

    Private Sub Command1_Click() Shell "C:\WINDOWS\COMMAND\EDIT.COM", vbNormalFocus End Sub

    Una unica instancia de la aplicacion corriendo a la vez...

    En el Sub Main() o en el Form_Load del 1er frm que cargues:

  • If App.Previnstance Then MsgBox "La aplicacion solicitada ya se esta ejecutando" 'Pon aqui el codigo para salir del programa '(Unload de los formularios cargados, set .. = nothing, etc.) End End If

    Ejecutar Microsoft Word desde VB

    Hay que hacer automatizacin, o sea, instanciar un objeto Word

    Dim oWord as new Word.ApplicationoWord.Visible = True 'Si quieres abrir un documento en blanco o uno concreto oWord.Documents.Add oWord.Documents.Open ""

    Bloquear el Boton Inicio, Crtl + Tab y Ctrl + Alt + Supr

    Declarar en un Mdulo lo siguiente:

    Public Declare Function SystemParametersInfo Lib "user32" Alias "SystemParametersInfoA" _ (ByVal uAction As Long, ByVal uParam As Long, ByVal lpvParam As Any, ByVal fuWinIni As Long) As Long

    (Ojo, toda esta declaracion debe estar en una sola linea!!)

    En el Evento Click del Form1 colocar lo siguiente:

    Sub Form_Click() Dim blnOld as Boolean If MsgBox ("Desea Bloquear ahora?", vbInformation + vbYesNo, "Bloqueo") = vbYes then SystemParametersInfo 97&, True, blnOld, 0& Else SystemParametersInfo 97&, False, blnOld, 0& End If End Sub

    Activar/Desactivar el Bloqueo de Mayusculas

    Solamente necesitamos declarar en un Modulo lo siguiente:

    Public Declare Function GetKeyboardState Lib "user32" Alias "GetKeyboardState" (pbKeyState As Byte) As Long

  • Public Declare Function SetKeyboardState Lib "user32" Alias "SetKeyboardState" (lppbKeyState As Byte) As Long

    Public Type KeyboardBytes kbByte(0 To 255) as Byte End Type

    En el Evento Click de la ventana (Form) colocaremos el siguiente codigo y nos fijaremos en la actitud de la lucecita del Bloqueo de Mayusculas...

    Private Sub Form_Click() Dim kbArray as KeyboardBytes GetKeyboardState kbArray kbArray.kbByte(&H14) = IIF(kbArray.kbByte(&H14) = 1, 0, 1) SetKeyboardState kbArray End Sub

    Cmo Activar el Protector de Pantallas?

    En un modulo, declarar lo siguiente:

    Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" _ (ByVal hwnd As Lo