Acmar trucos de visual basic(2)

452 views
379 views

Published on

trucos en visual basic ivan ramirez iglesias

Published in: Education
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
452
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
10
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Acmar trucos de visual basic(2)

  1. 1. Trucos de Visual Basic¿Como hacer una ventana siempre visible?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)Public Const HWND_TOPMOST& = -1Public Const SWP_NOMOVE& = &H2Public Const SWP_NOSIZE& = &H1Const FLAGS = SWP_NOMOVE Or SWP_NOSIZEPublic Sub ShowHoldForm(Ventana As Form)Dim Success**** Para las ventanitas que quedan por encima de las demás, ****Success = SetWindowPos(Ventana.hwnd, HWND_TOPMOST, 0, 0, 0, 0,FLAGS)End Sub-----------------------------ShowHoldForm Form1¿Cómo situar el puntero del ratón en el centro de un botón yluego "provocar" la pulsación del mismo?------En un móduloConst WM_LBUTTONDOWN = &H201Const WM_LBUTTONUP = &H202Private Declare Function PostMessageBynum Lib "user32" Alias "PostMessageA"_(ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long,ByVal lParam _As Long) As Long enviar mensajes al controlPrivate Declare Function SetCursorPos Lib "user32" (ByVal X As Long, ByVal _Y As Long) As Long posicionar el puntero del ratónPrivate Declare Function GetWindowRect Lib "user32" (ByVal hwnd As Long, _lpRect As RECT) As Long obtener la posición del controlPrivate Type RECTLeft As LongTop As LongRight As LongBottom As LongEnd Type----- ahora el proceso :Dim l As Long, PosX As Long, PosY As Long, PosXY As LongDim lpRect As RECT
  2. 2. conocer las posición del botón relativa a la pantalla, en pixelsl = GetWindowRect(Command1.hwnd, lpRect)colocar el ratón sobre el centro del botónPosX = lpRect.Left + ((lpRect.Right - lpRect.Left) / 2)PosY = lpRect.Top + ((lpRect.Bottom - lpRect.Top) / 2)l = SetCursorPos(PosX, PosY)obtener la posicion del centro del control relativa al propio control,en pixelsno es obligatorio, es para que las coordenadas recibidas en el mousedowndel control sean coherentesla posicion y va en la palabra alta y la x en la bajaPosXY = (PosY - lpRect.Top) * 65536 + (PosX - lpRect.Left)simular el click del ratónl = PostMessageBynum(Command1.hwnd, WM_LBUTTONDOWN, 0&, PosXY)l = PostMessageBynum(Command1.hwnd, WM_LBUTTONUP, 0&, PosXY)¿Como deshabilitar el CTRL+ALT+DELStart a new Standard EXE project. Form1 is created by default.Add two CommandButton controls (Command1 and Command2) to Form1.Add the following code to Form1s General Declarations section:-----------------------------Private Const SPI_SCREENSAVERRUNNING = 97&Private Declare Function SystemParametersInfo Lib "User32" _Alias "SystemParametersInfoA" _(ByVal uAction As Long, _ByVal uParam As Long, _lpvParam As Any, _ByVal fuWinIni As Long) As LongPrivate Sub Form_Load()Command1.Caption = "Disabled"Command2.Caption = "Enabled"End SubPrivate Sub Form_Unload(Cancel As Integer)Re-enable CTRL+ALT+DEL and ALT+TAB before the program terminates.Command2_ClickEnd SubPrivate Sub Command1_Click()Dim lngRet As LongDim blnOld As BooleanlngRet = SystemParametersInfo(SPI_SCREENSAVERRUNNING, True, _blnOld, 0&)End Sub
  3. 3. Private Sub Command2_Click()Dim lngRet As LongDim blnOld As BooleanlngRet = SystemParametersInfo(SPI_SCREENSAVERRUNNING, False, _blnOld, 0&)End SubPress the F5 key to run the program, and click the "Disabled"CommandButton. CTRL+ALT+DEL and ALT+TAB are disabled. Click the"Enabled" CommandButton to enable CTRL+ALT+DEL and ALT+TAB again.Saber si el programa ya se esta ejecutandoif app.previnstance then msgbox "Ya se esta ejecutando una instancia de esteprograma"¿Como copiar todas las tablas de una base de datos en unadestino?---Esta rutina sirve para copiar todas las tablas de una base de datos en unadestino.Si las tablas ya existian en la base de datos de eliminan y se vuelven a crear conla misma estructura que tuvieran en origenLas tablas de la base destino que no se encuentren en origen no se modifican.Si el parametro boCopiarDatos es true (valor por defecto) ademas deestructura se copian los datos de las tablas.Sub CopiaTablas(strOrigen As String, strDestino As String, OptionalboCopiarDatos As Boolean = True)Dim dbOrigen As Database, dbDestino As DatabaseDim tdOrigen As TableDef, tdDestino As TableDefDim fdOrigen As Field, fdDestino As FieldDim idOrigen As Index, idDestino As IndexDim prOrigen As Property, prDestino As PropertiesDim i As LongScreen.MousePointer = vbHourglass---abrir origen y destinoSet dbOrigen = OpenDatabase(strOrigen, False)Set dbDestino = OpenDatabase(strDestino, True)---hay propiedades que no se pueden copiar como el value de los camposOn Error Resume Next---para cada tabla de origenFor Each tdOrigen In dbOrigen.TableDefsIf (tdOrigen.Attributes And (dbSystemObject Or dbHiddenObject))---si la tabla no es del sistema---mirar si existe la tabla en destinoFor Each tdDestino In dbDestino.TableDefs
  4. 4. If tdDestino.Name = tdOrigen.Name Then---si existe la borrodbDestino.TableDefs.Delete tdDestino.NameExit ForEnd IfNext---creo la tabla en el destinoSet tdDestino = dbDestino.CreateTableDef(tdOrigen.Name, _tdOrigen.Attributes, tdOrigen.SourceTableName, tdOrigen.Connect)---le anado los camposFor Each fdOrigen In tdOrigen.FieldsSet fdDestino = tdDestino.CreateField(fdOrigen.Name, _fdOrigen.Type, fdOrigen.Size)---copio las propiedades del campoFor Each prOrigen In fdOrigen.PropertiesfdDestino.Properties(prOrigen.Name) =_fdOrigen.Properties(prOrigen.Name)NexttdDestino.Fields.Append fdDestinoNext---le anado los indicesFor Each idOrigen In tdOrigen.IndexesSet idDestino = tdDestino.CreateIndex(idOrigen.Name)---anado los campos al indiceFor Each fdOrigen In idOrigen.FieldsSet fdDestino = idDestino.CreateField(fdOrigen.NameidDestino.Fields.Append fdDestinoNext---copio las propiedades del indiceFor Each prOrigen In idDestino.PropertiesidDestino.Properties(prOrigen.Name) =idOrigen.Properties(prOrigen.Name)NexttdDestino.Indexes.Append idDestinoNextdbDestino.TableDefs.Append tdDestino---copio los datos de la tabla, si se solicitoIf boCopiarDatos Then dbOrigen.Execute ("INSERT INTO " + _tdDestino.Name + " IN " + strDestino + " SELECT * FROM " + tdDestiEnd IfNext---cerrar origen y destinodbOrigen.ClosedbDestino.CloseSet dbOrigen = Nothing: Set dbDestino = NothingSet tdOrigen = Nothing: Set tdDestino = NothingSet fdOrigen = Nothing: Set fdDestino = Nothing
  5. 5. Set idOrigen = Nothing: Set idDestino = NothingSet prOrigen = Nothing: Set prDestino = NothingScreen.MousePointer = vbDefaultEnd SubEsto soluciona lo de las búsquedas en los combos y no importa que tantosregistros tenga. para la autobúsqueda en los combosPublic Const CB_ERR = -1Public Const CB_FINDSTRING = &H14CPublic Const CB_FINDSTRINGEXACT = &H158Public Const CB_GETITEMDATA = &H150Declare Function SendMessage Lib "User32" Alias "SendMessageA" (ByValhWndAs Long, ByVal wMsg As Long, ByVal wParam As Long, lparam As Any) AsLong--- luego en el modulo hagan esta subrutina:Public Sub AutoMatch(cbo As ComboBox, KeyAscii As Integer)Dim sBuffer As StringDim lRetVal As LongsBuffer = Left(cbo.Text, cbo.SelStart) & Chr(KeyAscii)lRetVal = SendMessage((cbo.hWnd), CB_FINDSTRING, -1, ByVal sBuffer)If lRetVal <> CB_ERR Thencbo.ListIndex = lRetValcbo.Text = cbo.List(lRetVal)cbo.SelStart = Len(sBuffer)cbo.SelLength = Len(cbo.Text)KeyAscii = 0End IfEnd Sub----por ultimo en el combo con propiedad Style = 0 para que permitaescribir,escriben en el evento keypress lo siguiente:Private Sub Combo2_KeyPress(KeyAscii As Integer)AutoMatch Combo2, KeyAsciiEnd Sub¿Como añadir sonido a un programa?*** En un módulo:Public Declare Function sndPlaySound Lib "winmm.dll" _Alias "sndPlaySoundA" (ByVal lpszSoundName As String, _ByVal uFlags As Long) As LongPublic Const SND_LOOP = &H8Public Const SND_NODEFAULT = &H2Public Const SND_SYNC = &H0Public Const SND_ASYNC = &H1
  6. 6. Public Function PlaySound (FileName As String, F As Long) As LongPlaySound = sndPlaySound (FileName, F)End Function***Y para llamarla:PlaySound "C:WindowsMediaDing.wav", SND_ASYNC por ejemplo¿Como controlar el volumen?(archivo MMSYSTEM.DLL para 16bits y WINMM.DLL para 32)Declare Function waveOutGetVolume Lib "WINMM" (ByVal udeviceid As Integer,lpdwvolume As Long) As IntegerDeclare Function waveOutSetVolume Lib "WINMM" (ByVal udeviceid As Integer,ByVal dwVolume As Long) As IntegerDeclare Function midiOutSetVolume Lib "WINMM" (ByVal udeviceid As Integer,ByVal dwVolume As Long) As IntegerDeclare Function midiOutGetVolume Lib "WINMM" (ByVal udeviceid As Integer,lpdwvolume As Long) As IntegerDeclare Function auxOutGetVolume Lib "WINMM" (ByVal udeviceid As Integer,lpdwvolume As Long) As IntegerDeclare Function auxOutSetVolume Lib "WINMM" (ByVal udeviceid As Integer,ByVal dwVolume As Long) As IntegerImprimir un FORMPrinter.PrintFormImprimir un GráficoClipboard.ClearMSChart1.EditCopy Este pudiera ser tu objeto graficoPrinter.Print ""Printer.PaintPictureClipboard.GetData(), 0, 0Printer.EndDoc¿Cómo registrar un control?Ejecutar "REGSVR32 control.ocx"Esta es la forma de registrarlos manualmente (puede ser OCX, DLL, etc)¿Cómo reiniciar Windows?------------Declarar esta funcion en un modulo...Declare Function ExitWindowsEx& Lib "user32" (ByVal uFlags&, ByValdwReserved&)Public Const EWX_LOGOFF = 0Public Const EWX_SHUTDOWN = 1Public Const EWX_REBOOT = 2Public Const EWX_FORCE = 4-----------------------lresult = ExitWindowsEx(EWX_REBOOT, 0&) ---- Reinicia el sistema
  7. 7. lresult = ExitWindowsEx(EWX_SHUTDOWN, 0&) ---- Apaga el sistema¿Como cambiar la imagen del escritorio?Private Declare Function SystemParametersInfo Lib "user32" Alias _"SystemParametersInfoA" _(ByVal uAction As Long, ByVal uParam As Long, _ByVal lpvParam As String, ByVal fuWinIni As Long) As LongConst SPIF_UPDATEINIFILE = &H1Const SPI_SETDESKWALLPAPER = 20Const SPI_SETDESKPATTERN = 21Const SPIF_SENDWININICHANGE = &H2Private N As LongN = SystemParametersInfo(SPI_SETDESKWALLPAPER, 0&,_"c:MiDirectorioMiFichero.bmp", SPIF_SENDWININICHANGE OrSPIF_UPDATEINIFILE)¿Como detectar si estoy conectado a Internet?*************************************************************************** Declaraciones de la API***************************************************************************Option ExplicitPublic Declare Function RasEnumConnections Lib "RasApi32.dll" Alias"RasEnumConnectionsA"_(lpRasCon As Any, lpcb As Long, lpcConnections As Long) As LongPublic Declare Function RasGetConnectStatus Lib "RasApi32.dll" Alias"RasGetConnectStatusA"_(ByVal hRasCon As Long, lpStatus As Any) As LongPublic Const RAS95_MaxEntryName = 256Public Const RAS95_MaxDeviceType = 16Public Const RAS95_MaxDeviceName = 32Public Type RASCONN95dwSize As LonghRasCon As LongszEntryName(RAS95_MaxEntryName) As ByteszDeviceType(RAS95_MaxDeviceType) As ByteszDeviceName(RAS95_MaxDeviceName) As ByteEnd TypePublic Type RASCONNSTATUS95dwSize As LongRasConnState As Long
  8. 8. dwError As LongszDeviceType(RAS95_MaxDeviceType) As ByteszDeviceName(RAS95_MaxDeviceName) As ByteEnd Type*************************************************************************** DEVUELVE TRUE EN CASO DE ESTAR CONECTADO FALSE EN CASO CONTRARIO***************************************************************************Public Function IsConnected() As BooleanDim TRasCon(255) As RASCONN95Dim lg As LongDim lpcon As LongDim RetVal As LongDim Tstatus As RASCONNSTATUS95TRasCon(0).dwSize = 412lg = 256 * TRasCon(0).dwSizeRetVal = RasEnumConnections(TRasCon(0), lg, lpcon)If RetVal <> 0 ThenMsgBox "ERROR"Exit FunctionEnd IfTstatus.dwSize = 160RetVal = RasGetConnectStatus(TRasCon(0).hRasCon, Tstatus)If Tstatus.RasConnState = &H2000 ThenIsConnected = TrueElseIsConnected = FalseEnd IfEnd FunctionDesconectarse de Internet usando VB***Declarar en un móduloPublic Const RAS_MAXENTRYNAME As Integer = 256Public Const RAS_MAXDEVICETYPE As Integer = 16Public Const RAS_MAXDEVICENAME As Integer = 128Public Const RAS_RASCONNSIZE As Integer = 412Public Const ERR_SUCCESS As Integer = 0Public Type RasEntryNamedwSize As Long
  9. 9. szEntryName(RAS_MAXENTRYNAME) As ByteEnd TypePublic Type RasConndwSize As LonghRasConn As LongszEntryName(RAS_MAXENTRYNAME) As ByteszDeviceType(RAS_MAXDEVICETYPE) As ByteszDeviceName(RAS_MAXDEVICENAME) As ByteEnd TypePublic Declare Function RasEnumConnections Lib _"rasapi32.dll" Alias "RasEnumConnectionsA" (lpRasConn As Any, lpcb As Long, _lpcConnections As Long) As LongPublic Declare Function RasHangUp Lib "rasapi32.dll" Alias _"RasHangUpA" (ByVal hRasConn As Long) As LongPublic gstrISPName As StringPublic ReturnCode As Long******Añadimos estas dos funciones :Public Sub HangUp()Dim i As LongDim lpRasConn(255) As RasConnDim lpcb As LongDim lpcConnections As LongDim hRasConn As LonglpRasConn(0).dwSize = RAS_RASCONNSIZElpcb = RAS_MAXENTRYNAME * lpRasConn(0).dwSizelpcConnections = 0ReturnCode = RasEnumConnections( lpRasConn(0), lpcb, lpcConnections)If ReturnCode = ERROR_SUCCESS ThenFor i = 0 To lpcConnections - 1If Trim(ByteToString(lpRasConn(i).szEntryName)) = Trim(gstrISPName)ThenhRasConn = lpRasConn(i).hRasConnReturnCode = RasHangUp(ByVal hRasConn)End IfNext iEnd IfEnd SubPublic Function ByteToString(bytString() As Byte) As StringDim i As IntegerByteToString = ""i = 0While bytString(i) = 0&ByteToString = ByteToString & Chr(bytString(i))i = i + 1WendEnd Function
  10. 10. ***** Y para desconectar debemos hacer sólo :Call HangUp¿Como activar el salvapantallas desde VB?Private Declare Function SendMessage Lib "user32" Alias _"SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, _ByVal wParam As Long, lParam As Long) As LongPrivate Sub Command1_Click()Call SendMessage(Me.hwnd, &H112, &HF140, 0&)End Sub¿Alinear los iconos del escritorio?************************************************************ Declaraciones de la API para alinear los iconos************************************************************Private Declare Function GetWindow Lib "user32"_(ByVal hwnd As Long, ByVal wCmd As Long) As LongPrivate Declare Function SendMessage Lib "user32"_Alias "SendMessageA" (ByVal hwnd As Long,_ByVal wMsg As Long, ByVal wParam As Long, lParam As Long) As LongPrivate Declare Function FindWindow Lib "user32" _Alias "FindWindowA" (ByVal lpClassName As String, _ByVal lpWindowName As String) As LongPrivate Const GW_CHILD = 5Private Const LVA_ALIGNLEFT = &H1Private Const LVM_ARRANGE = &H1016************************************************************ Alinear los iconos del escritorio************************************************************Las instrucciones para alinear los iconos conDim hWnd1 As LongDim hWnd2 As LongDim Ret As LonghWnd1 = FindWindow("Progman", vbNullString)hWnd2 = GetWindow(hWnd1, GW_CHILD)hWnd1 = GetWindow(hWnd2, GW_CHILD)Ret = SendMessage(hWnd1, LVM_ARRANGE, LVA_ALIGNLEFT, 0)¿Como asociar un fichero a un programa determinado?************************************************************Windows API/Global Declarations for :AssociateFileType************************************************************Declare Function RegCreateKey& Lib "advapi32.DLL" Alias "_RegCreateKeyA" (ByVal hKey&, ByVal lpszSubKey$, lphKey&)
  11. 11. Declare Function RegSetValue& Lib "advapi32.DLL" _Alias "RegSetValueA" (ByVal hKey&, ByVal lpszSubKey$, _ByVal fdwType&, ByVal lpszValue$, ByVal dwLength&) Return codes from Registration functions.Public Const ERROR_SUCCESS = 0&Public Const ERROR_BADDB = 1&Public Const ERROR_BADKEY = 2&Public Const ERROR_CANTOPEN = 3&Public Const ERROR_CANTREAD = 4&Public Const ERROR_CANTWRITE = 5&Public Const ERROR_OUTOFMEMORY = 6&Public Const ERROR_INVALID_PARAMETER = 7&Public Const ERROR_ACCESS_DENIED = 8&Global Const HKEY_CLASSES_ROOT = &H80000000Public Const MAX_PATH = 256&Public Const REG_SZ = 1************************************************************ RUTINA QUE LE PERMITE ASOCIAR UN DETERMINADO TIPO DE FICHERO A UN PROGRAMA ASOCIA UN FICHERO CON EL BLOC DE NOTAS SE PUEDE CAMBIAR PARA ASOCIAR LOS QUE VD. QUIERA************************************************************Public Const ERROR_SUCCESS = 0&Public Const ERROR_BADDB = 1&Public Const ERROR_BADKEY = 2&Public Const ERROR_CANTOPEN = 3&Public Const ERROR_CANTREAD = 4&Public Const ERROR_CANTWRITE = 5&Public Const ERROR_OUTOFMEMORY = 6&Public Const ERROR_INVALID_PARAMETER = 7&Public Const ERROR_ACCESS_DENIED = 8&Global Const HKEY_CLASSES_ROOT = &H80000000Public Const MAX_PATH = 256&Public Const REG_SZ = 1Private Sub Command1_Click()Dim sKeyName As String NOMBRE DE LA CLAVE A REGISTRARDim sKeyValue As String NOMBRE DEL VALOR A REGISTRARDim ret& ERROR DEVUELTO POR LAS LLAMADAS A LA APIDim lphKey& HANDLE A LA CREACION DE REGTKEYsKeyName = "MyApp"sKeyValue = "My Application"ret& = RegCreateKey&(HKEY_CLASSES_ROOT, sKeyName, lphKey&)ret& = RegSetValue&(lphKey&, "", REG_SZ, sKeyValue, 0&) CREA UNA ENTRADA EN LA RAIZ LLAMADA .BAR PARA ASOCIALARLACON "MyApp".sKeyName = ".bar" *
  12. 12. sKeyValue = "MyApp" *ret& = RegCreateKey&(HKEY_CLASSES_ROOT, sKeyName, lphKey&)ret& = RegSetValue&(lphKey&, "", REG_SZ, sKeyValue, 0&) LINEA DE MANDATO "MyApp".sKeyName = "MyApp" *sKeyValue = "notepad.exe %1" *ret& = RegCreateKey&(HKEY_CLASSES_ROOT, sKeyName, lphKey&)ret& = RegSetValue&(lphKey&, "shellopencommand", REG_SZ, sKeyValue,MAX_PATH)End Sub¿Como puedo saber el espacio libre que queda en el disco?(FAT32)************************************************************ LLAMADAS A LA API************************************************************Declare Function GetDiskFreeSpaceEx Lib "kernel32" Alias _"GetDiskFreeSpaceExA" (ByVal lpRootPathName As String, _FreeBytesToCaller As LargeInt, BytesTotal As LargeInt, _FreeBytesTotal As LargeInt) As LongType LargeIntBytes(0 To 7) As ByteEnd Type************************************************************************ DEVUELVE EL ESPACIO LIBRE DE UN DISCO FORMATEADO CON FAT32************************************************************************Function GetFDS(Drive$)Dim FreeBytesToCaller As LargeIntBytesTotal As LargeIntFreeBytesTotalAs LargeIntDim i%GetDiskFreeSpaceEx Drive, FreeBytesToCaller, BytesTotal, FreeBytesTotalFor i = 0 to 7GetFDS = GetFDS + FreeBytesToCaller.Bytes(i) * 2 ^ (8 * i)Next iEnd Function¿Como copiar ficheros y que aparezcan los "papeles volando"?Private Sub Form_Activate()Dim result As LongDim fileop As SHFILEOPSTRUCTForm1.HideWith fileop.hwnd = Me.hwnd.wFunc = FO_COPY
  13. 13. .pFrom = "t:programsgestiongestion.exe" & vbNullChar & vbNullChar.pTo = "c:calipso" & vbNullChar & vbNullChar.fFlags = FOF_SIMPLEPROGRESS Or FOF_FILESONLYEnd Withresult = SHFileOperation(fileop)If result <> 0 ThenMsgBox "Operación cancelada"ElseIf fileop.fAnyOperationsAborted <> 0 ThenMsgBox "Operación fallida"End IfEnd IfUnload Form1End Sub Para que no pregunte si se quiere sustituir el fichero destino, en caso de queexista, añadir FOF_NOCONFIRMATION en la propiedad .fFlags =FOF_SIMPLEPROGRESS OrFOF_FILESONLY Or FOF_NOCONFIRMATION

×