| 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:
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: Uso de Random: Private Sub Form_Load() Dim Num As Double Num = Rnd MsgBox Num End Sub Nos daría como resultado siempre el mismo
número. Private Sub Form_Load() Dim Num As Double Randomize Num = Rnd MsgBox Num End Sub Calcular la etiqueta o label de un disco duro:
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:
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 módulo y escribir: Como obtener el directorio desde donde estamos
ejecutando nuestro programa: Determinar si un fichero existe o no:
Capturar la pantalla entera o la ventana
activa: Private Declare Sub keybd_event Lib "user32"
(ByVal bVk As Byte, Salvar el contenido de un TextBox a un fichero
en disco: Private Sub Command1_Click() Como desplegar la lista de un ComboBox
automáticamente: Nota: Resp = SendMessageLong(Combo1.hwnd, &H14F, False, 0) oculta la lista desplegada de un ComboBox, aunque esto sucede también cuando cambiamos el focus a otro control o al formulario. Selección y eliminación de todos los elementos
de un ListBox: Calcular el tamaño de fuentes de letra:
*) Esta función ha sido corregida por un error en las etiquetas, 96 corresponde a pequeñas y 120 a Grandes, agradecimientos a Andrés Moral Gutiérrez por su correción (01/06/1998) Provocar la trasparencia de un formulario:
Pasar de un TextBox a otro al pulsar Enter:
otra forma: Insertar tres TextBox, cambiar la propiedad KeyPreview del
formulario a True y escribir el siguiente código: Usar IF THEN ELSE ENDIF en una misma línea:
Private Sub Command1_Click() Convertir un texto a mayúsculas o
minúsculas: Presentar la ventana AboutBox
(Acerca de) por defecto: Incrementar un menú en
ejecución:
Cambiar el fondo de Windows desde
Visual Basic: Calcular el número de colores de
video del modo actual de Windows: Ajustar un Bitmap a la
pantalla: Escribir lo siguiente: Detectar la unidad del
CD-ROM: Crear un formulario con una etiqueta y escribir lo siguiente: Calcular
la profundidad de color (bits por pixel) y resolución de
Windows: Comprobar si el sistema posee
tarjeta de sonido: Crear una ventana con la información del
Sistema: Escribir lo siguiente en el módulo: Mostrar un fichero AVI a pantalla
completa: Crear un link con un programa añadiéndolo al grupo de programas situado en Inicio -> Programas o Start
-> Programs: Apagar el equipo, reiniciar
Windows, reiniciar el Sistema: Borrar un fichero y enviarlo a la
papelera de reciclaje: Private Type SHFILEOPSTRUCT El programa preguntará si deseamos o no eliminar el fichero y enviarlo a la papelera de reciclaje. El parámetro .fFlags nos permitirá recuperar el fichero de la papelera si lo deseamos. Si eliminamos esta línea, el fichero no podrá ser recuperado. Abrir el Acceso telefónico a Redes
de Windows y ejecutar una conexión: Private Sub Form_Load() Situar una ScroolBar horizontal en
un ListBox: Private Declare Function SendMessage Lib
"user32" Alias Obtener el nombre de usuario y de
la compañia de Windows:
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,
"SoftwareMicrosoftWindowsCurrentVersion",
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 números:
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 números:
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):
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
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 operación sólo es eficaz con el control Rich TextBox).
En un módulo copie esta línea:
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 instrucción de la función 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"
En un módulo copiar estas líneas:
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 botón en el formulario:
Label1, Label2, Command1
Hacer doble click sobre el botón y escribir el código 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 módulo copiar estas líneas:
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 código 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 líneas de X caracteres:
Añadir un TextBox con las propiedades "Multiline=True" y "ScrollBars=Vertical",
y un CommandButton. Hacer doble click sobre él y escribir este código:
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
Declaraciones generales en un módulo:
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 información en la línea de fichero Ini a la
que hacemos referencia. El fichero "Ejemplo.Ini" se creará automáticamente).
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 módulo el código de la función:
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
Crear un módulo 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 código 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 & " Número de clusters libres"
Label5.Caption = I4 & " Número 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 proyecto nuevo y escribir el código 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 botón):
Escribir el código siguiente en el módulo:
Declare Sub SetCursorPos Lib "User32" (ByVal X As Integer, ByVal Y As Integer)
Insertar un botón en el formulario y escribir el siguiente código:
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 implícito 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
Insertar el siguiente código en un módulo:
Declare Function mciExecute Lib "winmm.dll" (ByVal lpstrCommand As String) As Long
Insertar un botón en el formulario y escribir el siguiente código:
Private Sub Command1_Click()
iResult = mciExecute("Play c:windowsringin.wav")
End Sub
Hacer un formulario flotante al estilo de Visual Basic: Crear un nuevo proyecto, insertar un botón al formulario que inserte un formulario más y un módulo. Pegue el siguiente código en el módulo:
Declare Function SetParent Lib "user32" (ByVal hWndChild As Long, ByVal hWndNewParent As Long) As Long
Peguar el siguiente código 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 ejecución:
Crear un nuevo proyecto e insertar el siguiente código:
Private Sub Form_Load()
If App.PrevInstance Then
Msg = App.EXEName & ".EXE" & " ya está en ejecución"
MsgBox Msg, 16, "Aplicación."
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 Módulo:
Pegue el siguiente código 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 código en el módulo:
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 código 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 ratón:
Crear un nuevo proyecto e insertar dos ButtonClick y un Módulo:
Pegue el siguiente código 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 código en el módulo:
Declare Function ShowCursor Lib "user32" (ByVal bShow As Long) As Long
Calcular el número de serie de un disco:
Crear un nuevo proyecto e insertar el siguiente código 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
|