Documente Academic
Documente Profesional
Documente Cultură
Trucos VB
Trucos VB II
Trucos VB III
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
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:
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
ChDir App.Path
ChDrive App.Path
Directorio = App.Path
If Len(Directorio) > 3 Then
Directorio = Directorio & ""
End If
End Sub
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
i = (2 ^ GetDeviceCaps(Form1.hdc, 12)) ^
GetDeviceCaps(Form1.hdc, 14)
Text1.Text = CStr(i) & " colores."
End Sub
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)
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"
Barra (HScroll1.Value)
End Sub
En el evento Paint del formulario, escribir:
Private Sub Form_Paint()
Barra (HScroll1.Value)
End Sub
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
Trucos VB II
Trucos VB
Trucos VB II
Trucos VB III
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
Date$
no
son
equivalentes
La funcin Date$ devuelve la fecha del sistema en un string con el formato MM-DDAAAA. 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
Pasar
cadenas
de
caracteres
una
DLL
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
indentar
el
cdigo
Grabar
antes
de
ejecutar
Seleccionar
varios
controles
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:VBBIBLIO.MDB")
...
'
Cierro
DB.Close
'
Libero
la
memoria
Set DB = Nothing
Evitar
el
"beep"
del
[ENTER]
TextBox
de
slo
lectura
Error
al
utilizar
SetFocus
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
End UIT
Evitar
"Hola,
cadenas
nulas
en
Mundo!"
campos
de
Access
Usar
Sleep
en
lugar
de
DoEvents
Y
Sleep 0&
se
Error
al
usa
cambiar
de
el
la
tamao
siguiente
de
los
manera:
formularios
Entrar
1.
2.
3.
en
las
Propiedades
de
Crear
un
nuevo
formulario,
Form1
Aadir
un
boton
al
formulario
"Command
Aadir
el
siguiente
codigo
a
la
propieded
Private
X
=
End Sub
Shell("Rundll32.exe
Trucos VB III
Trucos VB
Trucos VB II
Sub
shell32.dll,Control_RunDLL
Accesibilidad
por
defecto
Button
control"
Clik
del
boton.
Command1_Click()
main.cpl
@2")
Trucos VB III
Combo1_GotFocus()
CB_SHOWDROPDOWN
=
&H14F
Tmp
SendMessage(Combo1.hwnd, CB_SHOWDROPDOWN, 1, ByVal 0&)
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
SendMessage(Text1.hWnd,
&HB8,
0,
Form1.Caption
=
"Se
ha
Form1.Caption
"Se
ha
End
ByVal
0&)
cambiado
dejado
igual
Form_Click()
=
1
then
el
Texto"
Else
el
Texto"
If
End Sub
Sub
Dim
Xs
Ys
SetWindowRgn
End Sub
Xs
=
=
hWnd,
as
Long,
Me.Width
/
Me.Height
/
CreateEllipticRng(0,
Form_Click()
Ys
as
Long
Screen.TwipsPerPixelX
Screen.TwipsPerPixelY
0,
Xs,
Ys),
True
1 Control DriveListBox
1 Control DirListBox
1 Control FileListBox
1 Control Picture1
1 Label1
El
Private
Codigo
colocar
es
Sub
File1.Path
el
siguiente:
Dir1_Change()
Dir1.Path
End Sub
Private
Sub
Dir1.Path
Drive1_Change()
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
File1.FileName
Sub
=
File1_PathChange()
"*.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
MDIForm.Arrange
Mosaico_Vertical_Click()
2
End Sub
Private
Sub
Mosaico_Horizontal_Click()
MDIForm.Arrange
1
End Sub
Private
End Sub
Un sencillo Cronmetro
Sub
MDIForm.Arrange
Cascada_Click()
0
Sub
Esperar(Tiempo
as
ComienzoTiempo
as
FinTiempo
as
ComienzoTiempo
=
FinTiempo
=
ComienzoTiempo
+
Do
While
FinTiempo
>
Do
If
ComienzoTiempo
>
Timer
FinTiempo
=
FinTiempo
24
*
60
End
Single)
Single
Single
Timer
Tiempo
Timer
Events
Then
*
60
If
Loop
End Sub
Para "llamarlo" desde un Form comun, colocar (por ejemplo, en el evento
Click)
Esperar(5)
Sub
KeyAscii
Text1_KeyPress(KeyAscii
As
Integer)
13 Or KeyAscii = 9 Then KeyAscii = 0
Nota: Para que sea mas fcil la escritura del codigo a colocar en el modulo, Visual
Basic trae el Visor de API de Windows
Sub
resultado
cmdOcultar_Click()
ShowCursor(False)
End Sub
Private
resultado
Sub
cmbMostrar_Click()
ShowCursor(True)
End Sub
Declare
If
Sub
Form1_KeyPress(KeyAscii
KeyAscii
=
SendKeys
KeyAscii
=
End
As
13
Integer)
Then
"{tab}"
0
If
End Sub
Sub
Resp
Dim
=
Resp
SetWindowLong(Me.hWnd,
As
Command1_Click()
Long
-20,
&H20&)
End
Form1.Refresh
Sub
Alias
String,
_
_
Private
Sub
Command1_Click()
Call ShellAbout(Me.hwnd, "Mi Programa", "Copyright 1999, PMMF", Me.Icon)
End Sub
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,
grafico_frm.grafico.ColumnCount
ReDim
label_y(1
=
To
'
de
Toma
i
For
i1
nota
=
If
0
label_y(i)
'
Nombre
If
un
slo
dato.
(Len(x2)
1)
/
3
grafico_frm.grafico.ColumnCount)
las
etiquetas
(y)
=
1
To
lista_cajeros.ListCount
1
lista_cajeros.Selected(i1)
Then
=
lista_cajeros.List(i1)
de
las
grafico_frm.grafico.Column
grafico_frm.grafico.ColumnLabel
=
i
=
i
i
=
(grafico_frm.grafico.ColumnCount
Exit
End
End
leyendas
=
+
+
i
label_y(i)
1
1)
Then
For
If
If
Next i1
For
i1
x
Next
For
For
Next
Next i1
i1
i1
i2
=
If
=
0
"'"
To
lista_datos.ListCount
lista_datos.Selected(i1)
+
lista_datos.List(i1)
Exit
End
1
Then
"'"
For
If
' Despus,
rellenas
los
datos.
=
1
To
grafico_frm.grafico.RowCount
=
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)
i2
PosicionHorizontal
MS
False
Exchange"
wPerfil
MAPISession1.SessionID
True
mensaje..."
=
""
As
New
=
Form
Form1
crptToWindow
Form1.hwnd
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
Edicion...
por
'
en
el
caso
de
que
'
como
se
cual
'
....
de
'
reviso
el
If
Form1.hWnd
=
....
'
End
'
reviso
el
If
form2.hWnd
=
....
'
hace
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
Dim
s
'//Codifica
XORStringEncrypt
Show
Print
'//Decodifica
XORStringEncrypt
Print
End
Sub
s
Form_Load()
String
"Hola!"
As
=
s,
"MiClave"
"Codificado:
";
s,
"Decodificado:
XORStringEncrypt(s
n
i
Char
"MiClave"
s
Sub
";
Private
Dim
Dim
Dim
Sub
As
String,
PassWord
As
As
As
n
For
Char =
Mid$(s,
Next
End Sub
=
i
=
1
Asc(Mid$(PassWord, (i Mod n) - n
i,
1)
=
Chr$(Asc(Mid$(s,
((i
i,
To
Mod
1))
As
String)
Long
Long
Long
Len(PassWord)
Len(s)
n) = 0), 1))
Xor
Char)
Leer
una
Cadena
(string)
dentro
de
otra...
En
particular
existen
muchos
comando
tales
CommandString="Source=File.txt;Path=C:CommonFiles;Title=;..."
conmo:
Function
As
As
As
Dim
Dim
nStartDelim
nEndDelim
nStartDelim
If
nStartDelim
nEndDelim
If
GetSubString
End
End
End
GetSubString(
String,
String,
String
As
=
=
=
=
Mid$(s,
As
As
InStr(s,
nStartDelim
nStartDelim
+
InStr(nStartDelim,
s,
nEndDelim
nStartDelim,
nEndDelim
_
_
_
_
String
Long
Long
StartDelim)
Then
Len(StartDelim)
EndDelim)
Then
nStartDelim)
If
If
Function
DE
gsDatabaseConnection
gsDatabaseName
=
As
New
dePPDMMirror
=
DE.cnnPPDMMirror.ConnectionString
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
Dim
AnotherCall
nDays
On
If
Randomize
AnotherCall
End
nDays
=
GetRandomDate
Exit
As
As
Error
Not
Boolean
Single
GoTo
AnotherCall
=
DateValue(EndDate)
CDate(DateValue(StartDate)
ErrorHandler:
GetRandomDate
End Function
ErrorHandler
Then
Timer
True
If
DateValue(StartDate)
nDays
*
Rnd())
Function
Null
Function
GenerateRandomFileName()
As
String
MASKNUM
As
String
=
"_0123456789"
MASKCHR
As
String
=
"abcdefghijklmnoprstuvwxyz"
MASK
As
String
=
MASKCHR
+
MASKNUM
MINLEN
As
Integer
=
4
MAXLEN
As
Integer
=
12
Dim
Dim
Dim
Dim
Dim
Dim
nFile
nMask
For
nChr
sFile
Next
nMask
For
nChr
sExt
Next
nMask
nFile
sFile
sExt
i
nChr
=
MINLEN
i
As
As
As
As
As
As
(MAXLEN
=
=
Int(nMask
sFile
+
=
=
Long
Long
String
String
Long
Long
MINLEN)
1
*
To
Rnd())
Mid$(MASK,
*
Rnd()
Len(MASK)
nFile
+
1
nChr,
1)
=
i
=
=
=
Int(nMask
sExt
+
1
*
Rnd())
Mid$(MASKCHR,
To
Len(MASKCHR)
3
+
1
nChr,
1)
GenerateRandomFileName
End Function
sFile
"." +
sExt
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") & ""
Function
=
Not
Hour(h)
+
Function
nHour
nMinutes
nSeconds
=
DecHour
=
End Function
HourDec(h
Minute(h)
DecHour(h
nHour
nMinutes
nSeconds
As
Variant)
As
IsNull(h)
/
60
+
Second(h)
As
Variant)
As
As
As
As
=
=
Int((h
nHour)
*
Int(((h
nHour)
*
60
nMinutes)
nHour
&
":"
&
nMinutes
&
":"
&
Variant
Then
/
3600
If
Function
Variant
Integer
Integer
Integer
Int(h)
60)
*
60)
nSeconds
Ejemplo:
Private
Dim
Dim
Cls
d
h
Print
"Hora
Print
"Hora
Print
"Hora
de
End Sub
Sub
h
d
=
=
Decimal
Estndar
Decimal
a
As
As
Command1_Click()
Single
String
Estndar
"10:37:58"
HourDec(d)
";
d
";
h
";
DecHour(h)
=
=
=
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
Dim
If
i
End
i
Plus
End Function
Function
Plus(Optional
i
Start
As
Variant)
As
IsMissing(Start)
Not
=
=
+
=
As
Long
Long
Then
Start-1
If
1
i
Esta pequea funcin puede ser extremadamente til en cdigo para obtener
recursos, digamos que es comn:
Dim
I=100
Caption
lblPINCode
fraAccount
optChecking.Caption
optSavings.Caption
...
As
Long
=
=
=
=
=
LoadResString(I)
+
I)
+
I)
+
I)
+
I)
LoadResString(1
LoadResString(2
LoadResString(3
LoadResString(4
cmdOK.Caption = LoadResString(n + I)
Supongamos que hacemos un cambio en el archivo recursos :
lblPINCode ya no
=
=
LoadResString(Plus(100))
LoadResString(Plus)
LoadResString(Plus)
LoadResString(Plus)
LoadResString(Plus)
lblPINCode =
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
Dim
i
As
Dim
n
As
Dim
rtn
As
n
=
For
i
=
0
rtn
=
rtn
If
i
<
rtn
=
rtn
End
Next
StrChain
=
End Function
Variant)
As
To
&
n
&
String
Integer
Integer
String
UBound(v)
n
v(i)
Then
vbCrLf
If
rtn
P.e:
Text1
"Hola",
"cmo",
"estas")
StrChain(
_
_
_
& "estas"
Claro, suponiendo que las cadenas concatenadas sean extensas, como un SQL o un
comando Script.
Function
Const
Const
aLf
=
MaxRead
Dim
Dim
Dim
Dim
Dim
IsBinaryFile(File
10,
aCR
=
ff
s
i
n
Rtn
As
String)
13,
^
As
As
As
As
As
aSP
15
As
Boolean
=
-
32
1
Integer
Integer
Integer
Integer
Boolean
On
Error
ff
Open
File
For
n
=
IIf(LOF(ff)
Do
i
=
If
i
IsBinaryFile
Rtn
Else
s
=
If
s
Else
If
s
=
Else
IsBinaryFile
Rtn
End
End
End
Loop
Close
Exit
IsBinaryFile_Err:
If
MsgBox "Error
GoTo
IsBinaryFile_Err
=
Binary
Access
Read
MaxRead,
MaxRead
-
>
i
>=
As
1,
1
Then
False
True
n
=
=
Asc(Input$(1,
aSP
>=
aCR
ff
verifying
Or
Until
file
File
#ff))
Then
aLf
Then
True
True
If
If
If
Rtn
ff
Function
Then
" &
FreeFile
#ff
LOF(ff))
&
Close
vbCrLf &
ff
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").
Single
Timer
Proceso
Private
Static
Sub
On
Echo(Optional
n
Error
As
As
String
Resume
"")
Long
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)
Explicit
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
Sub
admitir
txtText1_KeyPress(KeyAscii
dgitos,
el
punto
As
y
la
Integer)
coma
'si
If
se
pulsa
alguna
otra
tecla,
anular
la
pulsacin
de
InStr("0123456789.,",
Chr(KeyAscii))
=
0
KeyAscii
=
End
End Sub
Sub
If
Text1_Keypress(KeyAscii
KeyAscii
<>
'KeyAscii
=
8
es
el
If
KeyAscii
KeyAscii
End
As
Asc("9")
retroceso
o
<>
8
=
End
End Sub
teclado
Then
0
If
Integer)
Then
BackSpace
Then
0
If
If
Convertir
nmeros
txtText1_LostFocus()
False
then
Ingresar
SOLAMENTE
en
texto
Unidades$(9),
Decenas$(9),
Veintes$(9),
Function
Dim
DEC$,
Dim
'NUM#
var$
If
MILM$,
ReDim
var$,
=
=
InStr(var$,
Explicit
Oncenas$(9)
Centenas$(9)
Numlet$(NUM#)
MILL$,
MILE$,
UNID$
SALI$(11)
I%,
AUX$
Round(NUM#,
2)
Trim$(Str$(NUM#))
".") =
0
Then
var$
var$
End
If
var$
For
".00"
If
InStr(var$,
var$
".") =
Len(var$)
1
Then
=
var$
+
"0"
End
If
=
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)
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)
Decenas$(2)
Decenas$(3)
Decenas$(4)
Decenas$(5)
Decenas$(6)
Decenas$(7)
Decenas$(8)
Decenas$(9)
=
=
=
=
=
=
=
=
=
"DIEZ
"VEINTE
"TREINTA
"CUARENTA
"CINCUENTA
"SESENTA
"SETENTA
"OCHENTA
"NOVENTA
"
"
"
"
"
"
"
"
"
Oncenas$(1)
Oncenas$(2)
Oncenas$(3)
Oncenas$(4)
Oncenas$(5)
Oncenas$(6)
Oncenas$(7)
Oncenas$(8)
Oncenas$(9)
=
=
=
=
=
=
=
=
=
"ONCE
"DOCE
"TRECE
"CATORCE
"QUINCE
"DIECISEIS
"DIECISIETE
"DIECIOCHO
"DIECINUEVE
"
"
"
"
"
"
"
"
"
"VEINTIUNA
"VEINTIDOS
"VEINTITRES
"VEINTICUATRO
"VEINTICINCO
"VEINTISEIS
"
"
"
"
"
"
Veintes$(1)
Veintes$(2)
Veintes$(3)
Veintes$(4)
Veintes$(5)
Veintes$(6)
=
=
=
=
=
=
Veintes$(7)
Veintes$(8)
Veintes$(9)
=
=
=
Centenas$(1)
Centenas$(2)
Centenas$(3)
Centenas$(4)
Centenas$(5)
Centenas$(6)
Centenas$(7)
Centenas$(8)
Centenas$(9)
If
=
=
=
"
"
"
=
=
=
=
=
=
"
"
"
"
"
"VEINTISIETE
"VEINTIOCHO
"VEINTINUEVE
"
"
"
CIENTO
DOSCIENTOS
TRESCIENTOS
"CUATROCIENTOS
QUINIENTOS
SEISCIENTOS
SETECIENTOS
OCHOCIENTOS
NOVECIENTOS
"
"
"
"
"
"
"
"
"
NUM#
For
Centenas$(I%)
I%
=
=
2
To
9
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
rabes
(no
est
probado)
VerValor(Simbolo
As
Case
Case
String)
VerValor
As
Integer
Simbolo
"I"
1
"V"
5
"X"
10
"L"
50
"C"
100
"D"
500
"M"
1000
"Q"
5000
"H"
10000
Select
=
Case
VerValor
=
Case
VerValor
=
Case
VerValor
=
Case
VerValor
=
Case
VerValor
=
Case
VerValor
=
Case
VerValor
=
Case
VerValor
End
End Function
Convertir
nmeros
romanos
Function
Num2Roman(ByVal
a
N
rabes
As
-2Integer)
(no
est
As
probado)
String
Const
Dim
i
Temp
"IVXLCDM"
As
String
1
""
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
i
As
Digits
Integer,
Digit
As
=
=
=
Integer,
Temp
Sub
Text1.SelStart
Text1.SelLenght
=
=
Text1_GotFocus()
0
Len(Text1.Text)
End Sub
Private
Sub
Dim
Text1.Text
I
as
=
=
Text1_Change()
Integer
UCase(Text1.Text)
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
Localizamos
If
el
=
While
mayor
Long)
a
As
la
mayor
>
valor
String
funcin
Integer
String
Integer
exponente
0
True
Then
If
mayor
=
mayor
mayor
Loop
'
retorno
For
>
mayor
End
Exit
End
mayor
Calculamos
Then
1
If
Do
If
1
el
valor
=
a
If
=
valor
retorno
retorno
valor
mayor
<
=
To
0
(2
^
retorno
=
=
retorno
-
valor
End
Next
DecimalABinario
End Function
Step
a)
&
&
(2
binario
""
-1
Then
"0"
Else
"1"
a)
If
a
retorno
FindWindow(vbNullString,
abierta
Caption)
ventana
con
Then
titulo
Caption
If
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
Sub
Form_Load()
de
carga...
Me,
Private
If
EnabledToolBoxMenu
End
End Sub
True
Sub
Loading
Form_Activate()
Then
False
If
Me,
Ocultar
el
Puntero
del
Mouse
Private Declare Function ShowCursor Lib "user32" (ByVal bShow As Long) As Long
Private
Static
HideMouse
ShowCursor
End
Sub
HideMouse
=
As
Not
Timer1_Timer()
Boolean
HideMouse
HideMouse
Sub
Sub
"C:WINDOWSCOMMANDEDIT.COM",
Command1_Click()
vbNormalFocus
"La
aqui
de
App.Previnstance
Then
aplicacion
solicitada
ya
se
esta
ejecutando"
el
codigo
para
salir
del
programa
los
formularios
cargados,
set
.. =
nothing,
etc.)
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
Type
To
255)
as
KeyboardBytes
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
Dim
kbArray.kbByte(&H14)
Sub
kbArray
as
GetKeyboardState
=
IIF(kbArray.kbByte(&H14)
SetKeyboardState
End Sub
Form_Click()
KeyboardBytes
kbArray
=
1,
0,
1)
kbArray
Sub
SendMessage(Me.hWnd,
Command1_Click()
&HF140,
0&)
&H112,
End Sub
(ByVal
Las
Poner
Private
End
dos
Muestra
deben
Long
&H40
estar
en
una
misma
Linea)
botones
en
un
Form
y
escribir:
Sub
Command1_Click()
Ventana
=
FindWindow("Shell_Traywnd",
"
")
Call
SetWindowPos(Ventana,
0,
0,
0,
0,
0,
Oculta)
Sub
Private
Call
dos
declaraciones
as
(2)
Sub
SetWindowPos(Ventana,
0,
0,
0,
Command2_Click()
0,
0,
Muestra)
End Sub
Nota: Debe estar todo en una sola linea (Usar el Visor de Texto API, que
viene con Visual Basic)
Insertar el siguiente Codigo en el evento Click de un CommandButton
Private
Cambio
End Sub
Sub
Dim
Cambio
= SystemParametersInfo(20,
0,
Command1_Click()
as
Integer
"C:WindowsNubes.bmp", 0)
Sub
SHAddToRecentDocs
0,
Command1_Click()
0
End Sub
Nota: Esta sentencia No figura en el archivo de texto WinAPI, por lo que
debern tipearla tal cual est.-
String,
_
ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
Sub
Command1_Click()
Dim
X
as
Long
X = ShellExecute hWnd, "open", "mailto:lmbeber@hotmail.com", vbNullString,
vbNullString,
SW_SHOW
End Sub
cmdApagar
cmdReiniciarWindows
Declare
Dim
i
Sub
i
=
cmdApagar_Click()
As
Integer
ExitWindowsEx(1,
0&)
End Sub
Private
Declare
Dim
i
Sub
i
=
cmdReiniciarWindows_Click()
As
Integer
ExitWindowsEx(0,
0&)
End Sub
Private
Declare
Dim
i
End Sub
Sub
i
=
cmdReiniciarEquipo_Click()
As
Integer
ExitWindowsEx(2,
0&)
Sub
res
As
bVal
As
Command1.Caption
=
Command1.Caption
=
res
=
SystemParametersInfo(97,
Command1_Click()
Integer
Boolean
"Activado"
Then
"Desactivado"
True,
bVal,
0)
Command1.Caption
=
=
SystemParametersInfo(97,
"Desactivado"
bVal,
0)
If
Else
res
False,
End
End Sub
deshabilitar
estas
teclas:
Dim
lngRet
As
Long
Dim
blnOld
As
Boolean
lngRet = SystemParametersInfo(SPI_SCREENSAVERRUNNING, True, blnOld, 0&)
Para
volver
habilitarlas:
Dim
lngRet
As
Long
Dim
blnOld
As
Boolean
lngRet = SystemParametersInfo(SPI_SCREENSAVERRUNNING, False, blnOld, 0&)
Form_Load()
As
Long
As
Long
As
Long
As
Long
As
String
"C:/"
I1,
I2,
I3,
I4
=
Unidad
"
Sectores
por
cluster"
"
Bytes
por
sector"
Nmero
de
clusters
libres"
Nmero
total
de
clusters"
disco: " & (I1 * I2 * I4)
disco: " & (I1 * I2 * I3)
Sub
(Nota: Este cdigo vale igualmente para los CD-ROM y disquetes. La letra de la
unidad puede estar en letra minscula o mayscula).
Shell
("c:windowscommanddeltree.exe
c:eldirectorio
a
borrar")
Este ejemplo hara que eliminemos un directorio completo... quizas alguien deberia
probar con "/y" luego de deltree.exe para ver si pregunta o no... (Escucho
comentarios)
Const
Const
Sub
FO_DELETE
FOF_ALLOWUNDO
PapeleraDeReciclaje(ByVal
SHFileOp
As
RetVal
.wFunc
.pFrom
.fFlags
End
RetVal
End Sub
Private
PapeleraDeReciclaje
End Sub
Sub
=
=
&H3
&H40
Fichero
As
String)
SHFILEOPSTRUCT
As
Long
SHFileOp
=
FO_DELETE
=
Fichero
FOF_ALLOWUNDO
With
SHFileOperation(SHFileOp)
CommandButton1_Click()
"c:a.txt"
Sub
txtCampo_KeyPress(KeyAscii
As
Integer)
keyascii=0
End Sub
Web...
O
cualquier
otro
archivo
X = ShellExecute(Me.hWnd, "Open", "c:windowsmibmp.bmp", "", "c:windows", 1)
A esta funcin tu le proporcianars un archivo y ella se encargar de buscar y
ejecutar la aplicacin relacionada. Es casi mgica... (es como el sueo de cualquier
programador,
no?)
Para ejecutar la aplicacin de alguna forma deseada puedes usar los siguientes
valores de nShowCmd:
Const
SW_HIDE
As
Const
SW_SHOWNORMAL
As
Const
SW_SHOWMINIMIZED
As
Const
SW_SHOWMAXIMIZED
As
Const
SW_SHOWNOACTIVATE
As
Const
SW_SHOW
As
Const
SW_MINIMIZE
As
Const
SW_SHOWMINNOACTIVE
As
Const
SW_SHOWNA
As
Const
SW_RESTORE
As
Const SW_SHOWDEFAULT As Long = 10
Long
Long
Long
Long
Long
Long
Long
Long
Long
Long
=
=
=
=
=
=
=
=
=
=
0
1
2
3
4
5
6
7
8
9
Sub
mciExecute("
Play
Command1_Click()
C:WINDOWSRINGIN.WAV")
MMCONTROL1.FILENAME=("ruta
y
nombre
del
MMCONTROL1.COMMAND=OPEN
'para
abrir
MMCONTROL1.COMMAND=PLAY
'para
iniciar
MMCONTROL1.COMMAND=STOP
'para
parar
MMCONTROL1.COMMAND=CLOSE 'para cerrar el control
archivo
Mid")
el
control
la
ejecucin
la
ejecucin
Abrir
Cerrar.
=
=
=
=
1
5
1
5
'//cm
'//cm
'//cm
'//cm
pic_AnyName
vbCentimeters
vbCentimeters
vbCentimeters
=
=
=
(ptrX2
.Width,
.Image,
ptrX1),
(ptrY2
.Height,
=
=
_
ptrY1),
_
vbSrcCopy
vbPixels
vbPixels
CancelPrinting
Sub
Buffer
As
PrintPRNFile(PRNFile
As
Long
Chunk
numLoops
LeftOver
i
As
As
As
As
Boolean
As
=
String)
8192
String
Long
Long
Long
Dim
Dim
FCnl
PCnl
On
Error
As
As
Long
Long
GoTo
SubErr
'//Abre
el
archivo
y
el
port
de
Screen.MousePointer
=
CancelPrinting
=
FCnl
=
Open
PRNFile
For
Binary
Access
Read
PCnl
=
Open
CStr(Printer.Port)
For
Binary
Access
Write
'//Calcula
numLoops
LeftOver
'//lo
Chunk
For
Get
Put
DoEvents
If
Next
If
Chunk
Get
Put
End
el
tamao
archivo
Buffer
Buffer
LOF(1)
LOF(1)
Mod
imprime
Space$(Buffer)
numLoops
Chunk
Chunk
=
=
#FCnl,
#PCnl,
To
,
,
CancelPrinting
Then
Not
Exit
CancelPrinting
=
#FCnl,
#PCnl,
,
,
EndSub:
Close
Screen.MousePointer
Exit
SubErr:
MsgBox
Resume
End Sub
del
=
=
Err.Description,
impresora
vbHourglass
False
FreeFile
As
#FCnl
FreeFile
As
#PCnl
Then
Space$(LeftOver)
Chunk
Chunk
If
#FCnl,
#PCnl
vbDefault
Sub
vbInformation,
For
"Impresion
del
archivo..."
EndSub
RECOMENDACIONES.
Es conveniente colocar un Botn para configurar la Impresora antes de enviar el
trabajo (un archivo de impresora debe ejecutarse con el mismo controlador de la
impresora que lo creo). Adicionamos un control CommonDialog, y:
Private
cdlPrinterSetup.Flags
cdlPrinterSetup.ShowPrinter
Sub
=
cmdConfig_Click()
cdlPDPrintSetup
DoEvents
End Sub
Tambin es conveniente crear la opcin de cancelar:
Private
CancelPrinting
End Sub
Sub
cmdCancel_Click()
True
Dim
NumC
Sub
Sub
60
en
Text1,
este
Command1_Click()
ejmplo
60
ImprimeLineas(Texto
As
Object,
Linea
As
Integer)
Bloque
As
String
'Numero
de
caracteres
=
NumC
'Numero
de
Bloques
=
NumB
NumC,
NumB
As
Integer
=
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
'horizontal
Printer.EndDoc
Sub
Error
Printer.Print
RichTextBox1.SelPrint
GoTo
"
Command1_Click()
ElError
"
Printer.hDC
ElError:
End Sub
Hemos realizado una aplicacin y queremos que imprima UNA UNICA LINEA ante
determinados eventos y que no haga salto de pgina... (nos ha pasado?)
Hemos probado con el ENDDOC pero es lento (si solo espera imprimir una linea) y
ademas
hece
salto
de
pgina
por
cada
linea
escrita.
Pues bienSe puede imprimir utilizando el puerto paralelo con tres funciones de la
API:
-CreateFile
-WriteFile
-CloseHandle
Por
Ejemplo:
Private
Sub
Command1_Click()
Dim
res
As
Long
Dim
Linea
As
String
Dim
NumBytes
As
Long
Dim
BytesEscritos
As
Long
hImpresora = CreateFile("LPT1", GENERIC_WRITE, 0, ByVal 0&, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, &HFFFFFFFF) 'Esto va en una sola linea...
NumBytes
=
Len(Text1.Text)
Linea
=
String(NumBytes
+
2,
0)
Linea
=
Text1.Text
+
Chr$(13)
+
Chr$(10)
NumBytes
=
NumBytes
+
2
res = WriteFile(hImpresora, Linea, NumBytes, BytesEscritos, ByVal 0&)
res
=
CloseHandle(hImpresora)
End Sub
las declaraciones de las funciones son (varan un poco respecto a las del API
viewer):
Declare Function CreateFile Lib "kernel32" Alias "CreateFileA" (ByVal lpFileName As
String, ByVal dwDesiredAccess As Long, ByVal dwShareMode As Long,
lpSecurityAttributes As Any, ByVal dwCreationDisposition As Long, ByVal
dwFlagsAndAttributes As Long, ByVal hTemplateFile As Long) As Long
Declare Function WriteFile Lib "kernel32" (ByVal hFile As Long, ByVal lpBuffer As
String, ByVal nNumberOfBytesToWrite As Long, lpNumberOfBytesWritten As Long,
lpOverlapped As Any) As Long
Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
el
grfico...
Const
Const
Const
SRCCOPY
=
NEWFRAME
PIXEL
&HCC0020
=
1
3
'laslneassiguientes,debenestarcincortes,esdecirenunasola
linea.
Public Declare Function CreateCompatibleDC Lib "gdi32" Alias
"CreateCompatibleDC" (ByVal hdc As Long) As Long
PublicDeclareFunctionSelectObjectLib"gdi32"Alias"SelectObject"
(ByVal hdc As Long, ByVal hObject As Long) As Long
Public Declare Function StretchBlt Lib "gdi32" Alias "StretchBlt"
(ByValhdcAsLong,ByValxAsLong,ByValyAsLong,ByValnWidthAs
Long,ByValnHeightAsLong,ByValhSrcDCAsLong,ByValxSrcAsLong,
ByValySrcAsLong,ByValnSrcWidthAsLong,ByValnSrcHeightAsLong,
ByVal
dwRop
As
Long)
As
Long
Public Declare Function DeleteDC Lib "gdi32" Alias "DeleteDC" (ByVal
hdc
As
Long)
As
Long
PublicDeclareFunctionEscapeLib"gdi32"Alias"Escape"(ByValhdc
AsLong,ByValnEscapeAsLong,ByValnCountAsLong,ByVallpInData
AsString,lpOutDataAsAny)AsLong
Sub
Command1_Click()
Screen.MousePointer=11'relojdearena...sepuedeusarvbHourGlass
Picture1.Picture
Picture1.Image
'la funcin StretchBlt necesita coordenadas en Pixeles...
Picture1.ScaleMode
PIXEL
Printer.ScaleMode
PIXEL
Printer.Print
"
"
hMemoryDC%
hOldBitMap%
CreateCompatibleDC(Picture1.hDC)
SelectObject(hMemoryDC%, Picture1.Picture)
SelectObject(hMemoryDC%,
hOldBitmap%)
=
DeleteDC(hMemoryDC)
decir
el
bitmap
Scroll Animado
Esta es una rutina en Java Script que nos permite tener una animacin de texto
en la barra de estado del browser que estemos utilizando.
<Script
<!-//Propiedades
del
var
TextoMensaje
=
"(Aqui
var
DisplayLength
var pos = 1 - DisplayLength;
Function
(pos
for
scroll
==
if
sera
el
ScrollEnBarra()
scroll
var
if
Language="JavaScript">
TextoMensaje.Length)
(pos
(var
scroll
= scroll +
pos
i=1;
i
<=
=
scroll
TextoMensaje.substring(0,
scrll
texto
=
del
animado
mensaje)"
130
{
=
"";
pos++;
=
1
DisplayLength;
<
0)
{
math.abs(pos);
i++)
+
"
";
DisplayLength - i + 1);
}
acroll
//
SetTimeOut
scroll
La
else
+ TextoMensaje(substring(pos, ps + DisplayLength);
window.status
=
scroll;
velocidad
con
que
se
desplaza...
("ScrollEnBarra()",50);
}
ScrollEnBarra()
//-->
</Script>
y listo... A probarlo, viejo, que yo no tengo tiempo... Escucho comentarios!
Eliminar
la
pantalla
Cambiar
el
ttulo
Borrar la Password de Acceso...
de
Podremos:
Eliminar
Vamos
la
al
Editor
pantalla
del
registro
la
bienvenida...
ventana...
de
del
sistema
bienvenida...
(Regedit),
en
la
HKEY_CURRENT_USER/SOFTWARE/
Microsoft/Outlook
Express.
Creamos un nuevo valor DWORD, llamado NoSplash y le camos el valor 1.
rama
HKEY_CURRENT_USERSoftwareMicrosoftOutlook
Express. Creamos una entrada (Nuevo Valor de la cadena) llamada WindowTitle
(as, todo junto) y le ponemos el nombre que mas nos guste.
HKEY_LOCAL_MACHINESoftwareMicrosoftwindowscurrentVer
sionpolicies...
Aqui pulsamos en RATTINGS y aparecern dos valores: Default y Key. El que