Crear en Visual Basic Manual Part 2
Como desplegar la lista de un ComboBox automáticamente:

Insertar un ComboBox y un Botón en un nuevo proyecto y escribir el siguiente código:

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 también cuando cambiamos el focus a otro control o al formulario.


--------------------------------------------------------------------------------

Selección y eliminación de todos los elementos de un ListBox:


Insertar un ListBox y dos Botón en un nuevo proyecto. Poner la propiedad MultiSelect del ListBox
a "1 - Simple" y escriba el siguiente código:

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 tamaño de fuentes de letra:

Es útil para utilizar con la propiedad Resize sobre los controles al cambiar de resolución de pantalla.
Escribir el siguiente código:

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 = "Pequeñas
If ObCaps = 120 Then Cad = "Grandes"
MsgBox "Fuentes de letra " & Cad
End Sub


*) 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:

Escribir el siguiente código:

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 código:

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 código:

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 línea:


Insertar un CommandButton y un TextBox y escribir el siguiente código:


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 mayúsculas o minúsculas:

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 código 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, "Título Programa", "Copyright 1997, Dueño de la aplicación", Me.Icon)
End Sub



--------------------------------------------------------------------------------

Incrementar un menú en ejecución:

Abrir un proyecto nuevo, y haga doble click sobre el formulario. Meidante el gestór de menús
escribir lo siguiente:


Caption -> Editor
Name -> MnuEditor
Pulse Insertar y el botón "->"
Caption -> Añadir
Name -> MnuAñadir
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 código 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 MnuAñadir_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 número 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 aplicación 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 resolución 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 Información del Sistema:

Crear un formulario e insertar un módulo 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 módulo:

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 añadiéndolo 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:

Añadir tres botones a un formulario y escribir lo siguiente en el código 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 código:

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 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:

Crear un formulario y escribir el siguiente código:

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

Para Windows 2000/NT

V_ID_CONEXION = Shell ("rasphone.exe -d " & V_NOMBRE_DE_LA_CONEXION_DIAL-UP, 1)



--------------------------------------------------------------------------------

Situar una ScroolBar horizontal en un ListBox:Crear un formulario y escribir el siguiente código:
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 número final de la selección es el " & i
Next i
x = SendMessage(List1.hwnd, &H194, 200, ByVal 0&
End Sub

vea la parte 1 http://taringa.net/posts/info/2273239/Crear-en--Visual-Basic-Manual.html
vea la parte 3 http://taringa.net/posts/info/2273315/Crear-en-Visual-Basic-Manual-Part-3.html