Este sitio utiliza cookies propias y de terceros. Si continúa navegando consideramos que acepta el uso de cookies. OK Más Información.

[VB6] Coleccion de Codigos Utiles

  • 82 Respuestas
  • 55032 Vistas

0 Usuarios y 2 Visitantes están viendo este tema.

Desconectado Slore

  • *
  • Underc0der
  • Mensajes: 172
  • Actividad:
    0%
  • Reputación 0
  • OrwaySoftware
    • Ver Perfil
    • Email
  • Skype: OrwaySoftware
« Respuesta #60 en: Junio 09, 2012, 05:47:38 am »
Proceso repetido, finalizar hasta dejar uno solo
Modulo de Clase:
---------------------------------------------------------
Código:
Option Explicit
Private Const MAX_PATH& = 260
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Private Declare Function CreateToolhelpSnapshot Lib "kernel32" Alias "CreateToolhelp32Snapshot" (ByVal lFlags As Long, lProcessID As Long) As Long
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function GetCurrentProcessId Lib "kernel32" () As Long
Private Declare Function GetWindowThreadProcessId& Lib "user32" (ByVal hwnd As Long, lpdwProcessId As Long)
Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal blnheritHandle As Long, ByVal dwAppProcessId As Long) As Long
Private Declare Function ProcessFirst Lib "kernel32" Alias "Process32First" (ByVal hSnapshot As Long, uProcess As PROCESSENTRY32) As Long
Private Declare Function ProcessNext Lib "kernel32" Alias "Process32Next" (ByVal hSnapshot As Long, uProcess As PROCESSENTRY32) As Long
Private Declare Function RegisterServiceProcess Lib "kernel32" (ByVal ProcessID As Long, ByVal ServiceFlags As Long) As Long
Private Declare Function TerminateProcess Lib "kernel32" (ByVal ApphProcess As Long, ByVal uExitCode As Long) As Long

Private Type PROCESSENTRY32
dwSize As Long
cntUsage As Long
th32ProcessID As Long
th32DefaultHeapID As Long
th32ModuleID As Long
cntThreads As Long
th32ParentProcessID As Long
pcPriClassBase As Long
dwFlags As Long
szexeFile As String * MAX_PATH
End Type
Public Sub KillProcess(ByVal ProcessID As Long)
Dim hp&
hp& = OpenProcess(1&, -1&, ProcessID)
TerminateProcess hp&, 0&
DoEvents
End Sub

Public Function FindWindowByClass(ByVal WindowClassName As String) As Long
FindWindowByClass = FindWindow(WindowClassName, vbNullString)
End Function

Public Function FindProcessByWindowClass(ByVal WindowClassName As String) As Long
Dim pid&
GetWindowThreadProcessId FindWindowByClass(WindowClassName), pid&
FindProcessByWindowClass = pid&
End Function

Public Function FindProcessByName(ByVal AppPath As String) As Long
Dim AppPaths, ProcessIds, ParentProcessIds, i As Integer
ListRunningApps AppPaths, ProcessIds, ParentProcessIds
i = FindInArray(AppPaths, AppPath)
If i = -1 Then
FindProcessByName = 0
Else
FindProcessByName = ProcessIds(i)
End If
End Function

Public Sub ListRunningApps(ByRef AppPaths, ByRef ProcessIds, ByRef ParentProcessIds)
Dim uProcess As PROCESSENTRY32
Dim rProcessFound As Long
Dim hSnapshot As Long
Dim szExename As String
Dim i As Integer
Const TH32CS_SNAPPROCESS As Long = 2&

AppPaths = Array()
ProcessIds = Array()
ParentProcessIds = Array()

uProcess.dwSize = Len(uProcess)
hSnapshot = CreateToolhelpSnapshot(TH32CS_SNAPPROCESS, 0&)
rProcessFound = ProcessFirst(hSnapshot, uProcess)

Do While rProcessFound
i = InStr(1, uProcess.szexeFile, Chr(0))
szExename = LCase$(Left$(uProcess.szexeFile, i - 1))
AppendToArray AppPaths, szExename
AppendToArray ProcessIds, uProcess.th32ProcessID
AppendToArray ParentProcessIds, uProcess.th32ParentProcessID
rProcessFound = ProcessNext(hSnapshot, uProcess)
Loop
End Sub
Public Function FindInArray(List As Variant, Item As Variant) As Integer
Dim i As Integer
For i = 0 To UBound(List)
If UCase("" & List(i)) = UCase("" & Item) Then
FindInArray = i
Exit Function
End If
Next
FindInArray = -1
End Function
Private Sub AppendToArray(List As Variant, Item As Variant)
ReDim Preserve List(UBound(List) + 1)
List(UBound(List)) = Item
End Sub

----------------------------
este codigo en un formulario.
--------------------------------
Código:
Option Explicit
Private NombreProceso, IdentificacionProceso, ParentIdentificacionProceso
Private PM As Class1, i As Integer

Function Ejecutandoce(name As String)
Dim Veces As Integer
Veces = 0
Set PM = New Class1
PM.ListRunningApps NombreProceso, IdentificacionProceso, ParentIdentificacionProceso
For i = 0 To UBound(NombreProceso)
If NombreProceso(i) = name Then
Veces = Veces + 1
End If
Next

If Veces = 1 Then Exit Function

For i = 0 To UBound(NombreProceso)
If NombreProceso(i) = name Then
PM.KillProcess IdentificacionProceso(i)
Veces = Veces - 1
If Veces = 1 Then Exit Function
DoEvents
End If
Next

End Function

'Ejemplo para dejar la calculadora una sola vez en proceso en caso de que se 'este ejecutando mas de una vez
Private Sub Command1_Click()
Ejecutandoce ("calc.exe")
End Sub


Desconectado Slore

  • *
  • Underc0der
  • Mensajes: 172
  • Actividad:
    0%
  • Reputación 0
  • OrwaySoftware
    • Ver Perfil
    • Email
  • Skype: OrwaySoftware
« Respuesta #61 en: Junio 09, 2012, 05:47:59 am »
Como quitar los botones de un MDIForm (Parent)
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 Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long) As Long
Private Const WS_MINIMIZEBOX = &H20000
Private Const WS_MAXIMIZEBOX = &H10000
Private Const GWL_STYLE = (-16)
Private Const MF_BYPOSITION = &H400
Private Const MF_REMOVE = &H1000
Private Declare Function DrawMenuBar Lib "user32" _
       (ByVal hwnd As Long) As Long
Private Declare Function GetMenuItemCount Lib "user32" _
       (ByVal hMenu As Long) As Long
Private Declare Function GetSystemMenu Lib "user32" _
         (ByVal hwnd As Long, _
         ByVal bRevert As Long) As Long
Private Declare Function RemoveMenu Lib "user32" _
         (ByVal hMenu As Long, _
         ByVal nPosition As Long, _
         ByVal wFlags As Long) As Long
Private Const SC_MINIMIZE As Long = &HF020&
Private Const SC_MAXIMIZE As Long = &HF030&
Private Const MF_BYCOMMAND = &H0&
Private Const SC_CLOSE = &HF060&

Private Sub MDIForm_Load()
Dim L As Long
Dim hMenu As Long
Dim menuItemCount As Long
L = GetWindowLong(Me.hwnd, GWL_STYLE)
L = L And Not (WS_MINIMIZEBOX)
L = L And Not (WS_MAXIMIZEBOX)
L = SetWindowLong(Me.hwnd, GWL_STYLE, L)
hMenu = GetSystemMenu(Me.hwnd, 0)
If hMenu Then
      Call RemoveMenu(hMenu, SC_MAXIMIZE, MF_BYCOMMAND)
      Call RemoveMenu(hMenu, SC_MINIMIZE, MF_BYCOMMAND)
     menuItemCount = GetMenuItemCount(hMenu)
      Call RemoveMenu(hMenu, menuItemCount - 1, _
                       MF_REMOVE Or MF_BYPOSITION)
     Call RemoveMenu(hMenu, menuItemCount - 2, _
                       MF_REMOVE Or MF_BYPOSITION)
     Call DrawMenuBar(Me.hwnd)
End If
End Sub

Desconectado Slore

  • *
  • Underc0der
  • Mensajes: 172
  • Actividad:
    0%
  • Reputación 0
  • OrwaySoftware
    • Ver Perfil
    • Email
  • Skype: OrwaySoftware
« Respuesta #62 en: Junio 09, 2012, 05:48:43 am »
Encender y Apagar Num, Caps y Scroll Lock
Código:
Private Type OSVERSIONINFO
    dwOSVersionInfoSize As Long
    dwMajorVersion As Long
    dwMinorVersion As Long
    dwBuildNumber As Long
    dwPlatformId As Long
    szCSDVersion As String * 128
End Type
Private Declare Function GetVersionEx Lib "kernel32" Alias "GetVersionExA" (lpVersionInformation As OSVERSIONINFO) As Long
Private Declare Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)
Private Declare Function GetKeyboardState Lib "user32" (pbKeyState As Byte) As Long
Private Declare Function SetKeyboardState Lib "user32" (lppbKeyState As Byte) As Long
Const VK_NUMLOCK = &H90
Const VK_SCROLL = &H91
Const VK_CAPITAL = &H14
Const KEYEVENTF_EXTENDEDKEY = &H1
Const KEYEVENTF_KEYUP = &H2
Const VER_PLATFORM_WIN32_NT = 2
Const VER_PLATFORM_WIN32_WINDOWS = 1
Dim o As OSVERSIONINFO
Dim NumLockState As Boolean
Dim ScrollLockState As Boolean
Dim CapsLockState As Boolean


Aca podemos modificar el estado

Código:
Private Sub Num_Lock_Click()
o.dwOSVersionInfoSize = Len(o)
GetVersionEx o
Dim keys(0 To 255) As Byte
GetKeyboardState keys(0)
NumLockState = keys(VK_NUMLOCK)
If NumLockState <> True Then
    'Poner numlock a on
    If o.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS Then
        'Si es Win95
        keys(VK_NUMLOCK) = 1
        SetKeyboardState keys(0)
    ElseIf o.dwPlatformId = VER_PLATFORM_WIN32_NT Then
        'Si es WinNT
        keybd_event VK_NUMLOCK, &H45, KEYEVENTF_EXTENDEDKEY Or 0, 0
        keybd_event VK_NUMLOCK, &H45, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0
    End If
 Else
'Poner Num_Lock a Off
If o.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS Then
        keys(VK_NUMLOCK) = 0
        SetKeyboardState keys(0)
        ElseIf o.dwPlatformId = VER_PLATFORM_WIN32_NT Then
        keybd_event VK_NUMLOCK, &H45, KEYEVENTF_EXTENDEDKEY Or 0, 0
         keybd_event VK_NUMLOCK, &H45, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0
    End If
End If
End Sub


Lo demas es casi igual

Código:
Private Sub Caps_Lock_Click()
o.dwOSVersionInfoSize = Len(o)
GetVersionEx o
Dim keys(0 To 255) As Byte
GetKeyboardState keys(0)
CapsLockState = keys(VK_CAPITAL)
If CapsLockState <> True Then
    If o.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS Then
        keys(VK_CAPITAL) = 1
        SetKeyboardState keys(0)
    ElseIf o.dwPlatformId = VER_PLATFORM_WIN32_NT Then
        keybd_event VK_CAPITAL, &H45, KEYEVENTF_EXTENDEDKEY Or 0, 0
        keybd_event VK_CAPITAL, &H45, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0
    End If
 Else
 If o.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS Then
        keys(VK_CAPITAL) = 0
        SetKeyboardState keys(0)
    ElseIf o.dwPlatformId = VER_PLATFORM_WIN32_NT Then
        keybd_event VK_CAPITAL, &H45, KEYEVENTF_EXTENDEDKEY Or 0, 0
        keybd_event VK_CAPITAL, &H45, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0
    End If
End If
End Sub


Código:
Private Sub Scroll_Lock_Click()
o.dwOSVersionInfoSize = Len(o)
GetVersionEx o
Dim keys(0 To 255) As Byte
GetKeyboardState keys(0)
ScrollLockState = keys(VK_SCROLL)
If ScrollLockState <> True Then
    If o.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS Then
        keys(VK_SCROLL) = 1
        SetKeyboardState keys(0)
    ElseIf o.dwPlatformId = VER_PLATFORM_WIN32_NT Then
        keybd_event VK_SCROLL, &H45, KEYEVENTF_EXTENDEDKEY Or 0, 0
        keybd_event VK_SCROLL, &H45, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0
    End If
Else
If o.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS Then
        keys(VK_SCROLL) = 0
        SetKeyboardState keys(0)
    ElseIf o.dwPlatformId = VER_PLATFORM_WIN32_NT Then
        keybd_event VK_SCROLL, &H45, KEYEVENTF_EXTENDEDKEY Or 0, 0
        keybd_event VK_SCROLL, &H45, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0
    End If
End If
End Sub

_________________

Desconectado Slore

  • *
  • Underc0der
  • Mensajes: 172
  • Actividad:
    0%
  • Reputación 0
  • OrwaySoftware
    • Ver Perfil
    • Email
  • Skype: OrwaySoftware
« Respuesta #63 en: Junio 09, 2012, 05:49:03 am »
 Leer un Tag de un código HTML
Código:
Option Explicit
Option Compare Text

Function GetHTMLTag(ByVal Code As String, ByVal TagName As String) As String
Dim Inst1 As Long, Inst2 As Long
Dim opTagLen As Byte, clTagLen As Byte
Dim opTag As String, clTag As String

opTag = "<" & TagName & ">"
clTag = "</" & TagName & ">"
opTagLen = Len(opTag)
clTagLen = Len(clTag)

Inst1 = InStr(1, Code, opTag)
If Inst1 = 0 Then Exit Function          'Si no hay el Tag especificado se termina
Inst2 = InStr(Inst1 + opTagLen, Code, clTag)
If Mid(Code, Inst1 + opTagLen, _
        clTagLen) = clTag Then Exit Function  'Si hay etiqueta pero no hay
                                              'contenido [ej. <title></title>]
GetHTMLTag = Mid(Code, Inst1 + opTagLen, Inst2 - (Inst1 + opTagLen))
clTag = "": Code = ""
End Function


Esta función devuelve lo que esté escrito dentro del Tag que se especifique. NO hay que poner los símbolos de apertura y cierre del Tag (<> y </>).

NOTA: Es impresindible poner Option Compare Text para tratar mayusculas y minusculas igualmente

Desconectado Slore

  • *
  • Underc0der
  • Mensajes: 172
  • Actividad:
    0%
  • Reputación 0
  • OrwaySoftware
    • Ver Perfil
    • Email
  • Skype: OrwaySoftware
« Respuesta #64 en: Junio 09, 2012, 05:49:26 am »
Ejecutar un programa y esperar que finalice
'en un from
Option Explicit

Private Const PROCESS_QUERY_INFORMATION = &H400
Private Const STILL_ACTIVE = &H103
Private Declare Function OpenProcess Lib "kernel32" _
(ByVal dwDesiredAccess&, ByVal bInheritHandle&, ByVal dwProcessId&) _
As Long
Private Declare Function GetExitCodeProcess Lib "kernel32" _
(ByVal hProcess As Long, lpExitCode As Long) _
As Long

Sub EsperarShell(sCmd As String)

Dim hShell As Long
Dim hProc As Long
Dim codExit As Long

' ejecutar comando
hShell = Shell(Environ$("Comspec") & " /c " & sCmd, 2)

' esperar a que se complete el proceso
hProc = OpenProcess(PROCESS_QUERY_INFORMATION, False, hShell)

Do
GetExitCodeProcess hProc, codExit
DoEvents
Loop While codExit = STILL_ACTIVE

End Sub
'Ejemplo
Private Sub Command1_Click()
EsperarShell ("calc.exe")
msgbox "termino"
End Sub


Desconectado Slore

  • *
  • Underc0der
  • Mensajes: 172
  • Actividad:
    0%
  • Reputación 0
  • OrwaySoftware
    • Ver Perfil
    • Email
  • Skype: OrwaySoftware
« Respuesta #65 en: Junio 09, 2012, 05:49:48 am »
Autentificar Usuario y password (con referencia a bd)
Creamos un formulario con un text1, text2 y un cmd y pegamos este código (obviamente con la referencia a ADO y la base de datos ya armada):

Código:
Private cn1 As ADODB.Connection
Private rsusuario As ADODB.Recordset
Private strconn1 As String

Private Sub Form_Initialize()

strconn1 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\database.mdb"
Set cn1 = New ADODB.Connection

cn1.ConnectionString = strconn1
cn1.CursorLocation = adUseClient
cn1.Open

Set rsusuario = New ADODB.Recordset
rsusuario.Open "usuarios", cn1, adOpenDynamic, adLockOptimistic
End Sub

Private Sub Command1_Click()
On Error GoTo usermal
rsusuario.Find "usuario =" & "'" & Text1.Text & "'"
If rsusuario!password = Text2.Text Then
Form1.Show
vendedor = Text1.Text
Unload Me
Exit Sub
End If

usermal:
MsgBox "El usuario o el password es incorrecto"
End

End Sub


Desconectado Slore

  • *
  • Underc0der
  • Mensajes: 172
  • Actividad:
    0%
  • Reputación 0
  • OrwaySoftware
    • Ver Perfil
    • Email
  • Skype: OrwaySoftware
« Respuesta #66 en: Junio 09, 2012, 05:57:29 am »
Como pasar de un TextBox a otro pulsando ENTER
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:

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


Agrego algo mas facil, sensillo, y mas eficiente.

'---------------------------------
Código:
Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii = 13 Then
KeyAscii = 0
Text2.SetFocus
End If
End Sub

'---------------------------------

Lo que hace es, al detectar que se aprieta el Ascii 13 (que es el ENTER), pone como foco el Text2, es decir, pone el cursor sobre el Text2.

Es mas eficiente que el SendKey, por que si se usa sendkey, lo que hace es emular que se aprieta el TAB... y si usan SendKey, van a tener que asignarle por ejemplo al Text1 TAB1 y al Text2 TAB2, osea la propiedad de propiedad TAB de cada textbox, hay que poner al siguiente text que se quiere que salte un numero consecutivo.


Desconectado Slore

  • *
  • Underc0der
  • Mensajes: 172
  • Actividad:
    0%
  • Reputación 0
  • OrwaySoftware
    • Ver Perfil
    • Email
  • Skype: OrwaySoftware
« Respuesta #67 en: Junio 09, 2012, 05:57:54 am »
Programa que registra sus ocx y dll
Esta es una técnica que pongo mucho en practica y la voy a compartir con ustedes. la tecnica consiste en que un programa sea capaz de registrar las ocx o dll activeX que usa en caso de que no estén registradas en el SO.

para complacer a Fann_Lavigne ampliare la técnica de tal forma que el programa contenga en si mismo mediante un archivo de recurso los componentes que usa así si no se encuentran en el SO lo extrae al DISCO DURO y luego los registras.

1-Creando el archivo de recursos.
creamos un archivo *.txt con el contenido siguiente:

1 componente PRELOAD WinPaht.ocx

luego le cambiamos la extensión por *.rc y lo nombramos componect.rc

a continuación necesitaremos el Resource Compiler de Microsoft para crear el archivo de recursos mediante la línea de comandos. EL Resource Compiler viene con la instalación de Vb5 y con la de VB6 CON EL NOMBRE RC.EXE

para eso usaremos un *.bat que lo llamaremos crearrecurso.bat con el contenido siguiente:
RC.EXE componect.rc

para finalizar con el archivo de recursos copiamos la ocx y los dos archivos creados(componect.rc y crearrecurso.bat) en la carpeta donde se encuentra RC.EXE. y ejecutamos el *.bat. se creara el archivo componect.res que añadiremos a nuestro programa presionando Ctrl+D.

ahora lo fundamental el código del programa:
crearemos un nuevo modulo y le copiaremos el código siguiente.
'Requiere Win32 SDK functions to register/unregister any ActiveX component

Código:
Private Declare Function LoadLibraryRegister Lib "KERNEL32" Alias "LoadLibraryA" _
(ByVal lpLibFileName As String) As Long

Private Declare Function FreeLibraryRegister Lib "KERNEL32" Alias "FreeLibrary" _
(ByVal hLibModule As Long) As Long

Private Declare Function CloseHandle Lib "KERNEL32" (ByVal hObject As Long) As Long
Private Declare Function GetProcAddressRegister Lib "KERNEL32" Alias "GetProcAddress" _
(ByVal hModule As Long, _
ByVal lpProcName As String) As Long

Private Declare Function CreateThreadForRegister Lib "KERNEL32" Alias "CreateThread" _
(lpThreadAttributes As Any, ByVal dwStackSize As Long, ByVal lpStartAddress As Long, _
ByVal lpparameter As Long, ByVal dwCreationFlags As Long, lpThreadID As Long) As Long

Private Declare Function WaitForSingleObject Lib "KERNEL32" _
(ByVal hHandle As Long, _
ByVal dwMilliseconds As Long) As Long

Private Declare Function GetExitCodeThread Lib "KERNEL32" _
(ByVal hThread As Long, lpExitCode As Long) As Long

Private Declare Sub ExitThread Lib "KERNEL32" (ByVal dwExitCode As Long)

Private Const STATUS_WAIT_0 = &H0
Private Const WAIT_OBJECT_0 = ((STATUS_WAIT_0) + 0)

Public Enum REGISTER_FUNCTIONS
DllRegisterServer = 1
DllUnRegisterServer = 2
End Enum

Public Enum STATUS
[File Could Not Be Loaded Into Memory Space] = 1
[Not A Valid ActiveX Component] = 2
[ActiveX Component Registration Failed] = 3
[ActiveX Component Registered Successfully] = 4
[ActiveX Component UnRegistered Successfully] = 5
End Enum


Sub Main()
On Error GoTo error
Form1.Show
Exit Sub
error:
MsgBox "El programa creara el componente WinPaht.ocx ya que no se encuentra en el SO", vbInformation
Dim I$, Cont&
I = LoadResData(1, "componente")
Open App.Path & "\WinPaht.ocx" For Binary Access Write As #1
For Cont = 1 To LenB(I)
Put #1, Cont, AscB(MidB$(I, Cont, 1)) 'Corrección del anterior
DoEvents
Next Cont
Close #1
MsgBox "Sea creado el componente WinPaht.ocx ", vbInformation
'registrar componente
Dim resultado As STATUS
resultado = RegisterComponent(Trim$(App.Path & "\WinPaht.ocx"), DllRegisterServer)
If resultado = [File Could Not Be Loaded Into Memory Space] Then
MsgBox "El Archivo No Pudo Estar Cargado en Espacio de Memoria", vbExclamation
ElseIf resultado = [Not A Valid ActiveX Component] Then
MsgBox "Componente ActiveX no valido", vbExclamation
ElseIf resultado = [ActiveX Component Registration Failed] Then
MsgBox "El Registro del componente a fallado", vbExclamation
ElseIf resultado = [ActiveX Component Registered Successfully] Then
MsgBox "Componente ActiveX Registrado correctamente", vbExclamation
End If
Main
End Sub

Private Function RegisterComponent(ByVal FileName$, _
ByVal RegFunction As REGISTER_FUNCTIONS) As STATUS

Dim lngLib&, lngProcAddress&, lpThreadID&, fSuccess&, dwExitCode&, hThread&

If FileName = "" Then Exit Function

lngLib = LoadLibraryRegister(FileName)
If lngLib = 0 Then
RegisterComponent = [File Could Not Be Loaded Into Memory Space] 'Couldn't load component
Exit Function
End If

Select Case RegFunction
Case REGISTER_FUNCTIONS.DllRegisterServer
lngProcAddress = GetProcAddressRegister(lngLib, "DllRegisterServer")
Case REGISTER_FUNCTIONS.DllUnRegisterServer
lngProcAddress = GetProcAddressRegister(lngLib, "DllUnregisterServer")
Case Else
End Select

If lngProcAddress = 0 Then
RegisterComponent = [Not A Valid ActiveX Component]
If lngLib Then Call FreeLibraryRegister(lngLib)
Exit Function
Else
hThread = CreateThreadForRegister(ByVal 0&, 0&, ByVal lngProcAddress, ByVal 0&, 0&, lpThreadID)
If hThread Then
fSuccess = (WaitForSingleObject(hThread, 10000) = WAIT_OBJECT_0)
If Not fSuccess Then
Call GetExitCodeThread(hThread, dwExitCode)
Call ExitThread(dwExitCode)
RegisterComponent = [ActiveX Component Registration Failed]
If lngLib Then Call FreeLibraryRegister(lngLib)
Exit Function
Else
If RegFunction = DllRegisterServer Then
RegisterComponent = [ActiveX Component Registered Successfully]
ElseIf RegFunction = DllUnRegisterServer Then
RegisterComponent = [ActiveX Component UnRegistered Successfully]
End If
End If
Call CloseHandle(hThread)
If lngLib Then Call FreeLibraryRegister(lngLib)
End If
End If
End Function


para terminar solo tienen que ir a las propiedades del proyecto y poner como objeto inicial Sub Main

Desconectado Slore

  • *
  • Underc0der
  • Mensajes: 172
  • Actividad:
    0%
  • Reputación 0
  • OrwaySoftware
    • Ver Perfil
    • Email
  • Skype: OrwaySoftware
« Respuesta #68 en: Junio 09, 2012, 06:12:08 am »
Programa que registra sus ocx y dll
Esta es una técnica que pongo mucho en practica y la voy a compartir con ustedes. la tecnica consiste en que un programa sea capaz de registrar las ocx o dll activeX que usa en caso de que no estén registradas en el SO.

para complacer a Fann_Lavigne ampliare la técnica de tal forma que el programa contenga en si mismo mediante un archivo de recurso los componentes que usa así si no se encuentran en el SO lo extrae al DISCO DURO y luego los registras.

1-Creando el archivo de recursos.
creamos un archivo *.txt con el contenido siguiente:

1 componente PRELOAD WinPaht.ocx

luego le cambiamos la extensión por *.rc y lo nombramos componect.rc

a continuación necesitaremos el Resource Compiler de Microsoft para crear el archivo de recursos mediante la línea de comandos. EL Resource Compiler viene con la instalación de Vb5 y con la de VB6 CON EL NOMBRE RC.EXE

para eso usaremos un *.bat que lo llamaremos crearrecurso.bat con el contenido siguiente:
RC.EXE componect.rc

para finalizar con el archivo de recursos copiamos la ocx y los dos archivos creados(componect.rc y crearrecurso.bat) en la carpeta donde se encuentra RC.EXE. y ejecutamos el *.bat. se creara el archivo componect.res que añadiremos a nuestro programa presionando Ctrl+D.

ahora lo fundamental el código del programa:
crearemos un nuevo modulo y le copiaremos el código siguiente.
'Requiere Win32 SDK functions to register/unregister any ActiveX component

Código:
Private Declare Function LoadLibraryRegister Lib "KERNEL32" Alias "LoadLibraryA" _
(ByVal lpLibFileName As String) As Long

Private Declare Function FreeLibraryRegister Lib "KERNEL32" Alias "FreeLibrary" _
(ByVal hLibModule As Long) As Long

Private Declare Function CloseHandle Lib "KERNEL32" (ByVal hObject As Long) As Long
Private Declare Function GetProcAddressRegister Lib "KERNEL32" Alias "GetProcAddress" _
(ByVal hModule As Long, _
ByVal lpProcName As String) As Long

Private Declare Function CreateThreadForRegister Lib "KERNEL32" Alias "CreateThread" _
(lpThreadAttributes As Any, ByVal dwStackSize As Long, ByVal lpStartAddress As Long, _
ByVal lpparameter As Long, ByVal dwCreationFlags As Long, lpThreadID As Long) As Long

Private Declare Function WaitForSingleObject Lib "KERNEL32" _
(ByVal hHandle As Long, _
ByVal dwMilliseconds As Long) As Long

Private Declare Function GetExitCodeThread Lib "KERNEL32" _
(ByVal hThread As Long, lpExitCode As Long) As Long

Private Declare Sub ExitThread Lib "KERNEL32" (ByVal dwExitCode As Long)

Private Const STATUS_WAIT_0 = &H0
Private Const WAIT_OBJECT_0 = ((STATUS_WAIT_0) + 0)

Public Enum REGISTER_FUNCTIONS
DllRegisterServer = 1
DllUnRegisterServer = 2
End Enum

Public Enum STATUS
[File Could Not Be Loaded Into Memory Space] = 1
[Not A Valid ActiveX Component] = 2
[ActiveX Component Registration Failed] = 3
[ActiveX Component Registered Successfully] = 4
[ActiveX Component UnRegistered Successfully] = 5
End Enum


Sub Main()
On Error GoTo error
Form1.Show
Exit Sub
error:
MsgBox "El programa creara el componente WinPaht.ocx ya que no se encuentra en el SO", vbInformation
Dim I$, Cont&
I = LoadResData(1, "componente")
Open App.Path & "\WinPaht.ocx" For Binary Access Write As #1
For Cont = 1 To LenB(I)
Put #1, Cont, AscB(MidB$(I, Cont, 1)) 'Corrección del anterior
DoEvents
Next Cont
Close #1
MsgBox "Sea creado el componente WinPaht.ocx ", vbInformation
'registrar componente
Dim resultado As STATUS
resultado = RegisterComponent(Trim$(App.Path & "\WinPaht.ocx"), DllRegisterServer)
If resultado = [File Could Not Be Loaded Into Memory Space] Then
MsgBox "El Archivo No Pudo Estar Cargado en Espacio de Memoria", vbExclamation
ElseIf resultado = [Not A Valid ActiveX Component] Then
MsgBox "Componente ActiveX no valido", vbExclamation
ElseIf resultado = [ActiveX Component Registration Failed] Then
MsgBox "El Registro del componente a fallado", vbExclamation
ElseIf resultado = [ActiveX Component Registered Successfully] Then
MsgBox "Componente ActiveX Registrado correctamente", vbExclamation
End If
Main
End Sub

Private Function RegisterComponent(ByVal FileName$, _
ByVal RegFunction As REGISTER_FUNCTIONS) As STATUS

Dim lngLib&, lngProcAddress&, lpThreadID&, fSuccess&, dwExitCode&, hThread&

If FileName = "" Then Exit Function

lngLib = LoadLibraryRegister(FileName)
If lngLib = 0 Then
RegisterComponent = [File Could Not Be Loaded Into Memory Space] 'Couldn't load component
Exit Function
End If

Select Case RegFunction
Case REGISTER_FUNCTIONS.DllRegisterServer
lngProcAddress = GetProcAddressRegister(lngLib, "DllRegisterServer")
Case REGISTER_FUNCTIONS.DllUnRegisterServer
lngProcAddress = GetProcAddressRegister(lngLib, "DllUnregisterServer")
Case Else
End Select

If lngProcAddress = 0 Then
RegisterComponent = [Not A Valid ActiveX Component]
If lngLib Then Call FreeLibraryRegister(lngLib)
Exit Function
Else
hThread = CreateThreadForRegister(ByVal 0&, 0&, ByVal lngProcAddress, ByVal 0&, 0&, lpThreadID)
If hThread Then
fSuccess = (WaitForSingleObject(hThread, 10000) = WAIT_OBJECT_0)
If Not fSuccess Then
Call GetExitCodeThread(hThread, dwExitCode)
Call ExitThread(dwExitCode)
RegisterComponent = [ActiveX Component Registration Failed]
If lngLib Then Call FreeLibraryRegister(lngLib)
Exit Function
Else
If RegFunction = DllRegisterServer Then
RegisterComponent = [ActiveX Component Registered Successfully]
ElseIf RegFunction = DllUnRegisterServer Then
RegisterComponent = [ActiveX Component UnRegistered Successfully]
End If
End If
Call CloseHandle(hThread)
If lngLib Then Call FreeLibraryRegister(lngLib)
End If
End If
End Function


para terminar solo tienen que ir a las propiedades del proyecto y poner como objeto inicial Sub Main

Desconectado Slore

  • *
  • Underc0der
  • Mensajes: 172
  • Actividad:
    0%
  • Reputación 0
  • OrwaySoftware
    • Ver Perfil
    • Email
  • Skype: OrwaySoftware
« Respuesta #69 en: Junio 09, 2012, 06:12:24 am »
Como apagar el monitor
Código:
Private Const APAGA = 2&
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 Command1_Click()
Call SendMessage(Me.hWnd, &H112, &HF170&, ByVal APAGA)
End Sub

Desconectado Slore

  • *
  • Underc0der
  • Mensajes: 172
  • Actividad:
    0%
  • Reputación 0
  • OrwaySoftware
    • Ver Perfil
    • Email
  • Skype: OrwaySoftware
« Respuesta #70 en: Junio 09, 2012, 06:12:45 am »
Buscar todas las palabras iguales que uno desee y cambiar co
Código:
'Este codigo fue programado por CULD
'-----------------------------------
'Lo que hace es... cambiar de color
'todas las palabras que encuentre
'en el RichTextBox que uno quiera.
'por el color que uno  quiera
'-----------------------------------
'Para llamar a la accion hay que usar
'Call Colorear(Palabra, "El RichTextBox", Color, 1)
'El Richtextbox es el nombre donde va a colorear
'El color tiene que ser en Hexadecimal (pueden cambiar el color de un label y copiar el codigo)
'La posicion por default siempre tiene que ser 1, si es que se quiere colorear desde el comienzo
'si se quiere colorear desde donde esta el cursor, hay que usar SelStart
Public Sub Colorear(Palabra As String, Objeto As Object, Color As String, Posicion As Long)
Dim Texto As String
Dim Estoy As Long
Texto = Objeto.Text

Estoy = InStr(Posicion, Texto, Palabra, vbTextCompare)
If Estoy > 0 Then
    'Se posiciona el cursor donde encontro la palabra
    Objeto.SelStart = Estoy - 1
    'Selecciona toda la palabra
    Objeto.SelLength = Len(Palabra)
    'Colorea la palabra
    Objeto.SelColor = Color
    'Pone en la posicion al final de la palabra
    Posicion = Estoy + Len(Palabra)
    'vuelve a llamar a la accion recursivamente para encontrar todas las palabras
    Call Colorear(Palabra, Objeto, Color, Posicion)
Else
    Exit Sub
End If
End Sub

_________________
Imagen

Desconectado Slore

  • *
  • Underc0der
  • Mensajes: 172
  • Actividad:
    0%
  • Reputación 0
  • OrwaySoftware
    • Ver Perfil
    • Email
  • Skype: OrwaySoftware
« Respuesta #71 en: Junio 09, 2012, 06:13:07 am »
-crearemos un proyecto exe standar.
-un TextBox de nombre=COMANDOS y con la propiedad MULTILINE=tRUE
-UN COMANDBUTTON
y copiaremos el codigo siguiente en el Form:

Código:
Option Explicit

Private Const PROCESS_QUERY_INFORMATION = &H400
Private Const STILL_ACTIVE = &H103
Private Declare Function OpenProcess Lib "kernel32" _
(ByVal dwDesiredAccess&, ByVal bInheritHandle&, ByVal dwProcessId&) _
As Long
Private Declare Function GetExitCodeProcess Lib "kernel32" _
(ByVal hProcess As Long, lpExitCode As Long) _
As Long

Sub EjecutarCMDDOS(COMANDOS As String)

Dim hShell As Long
Dim hProc As Long
Dim codExit As Long

Open "Archivo.bat" For Output As #1
Print #1, COMANDOS
Close #1
' ejecutar comando
hShell = Shell(Environ$("Comspec") & " /c " & "Archivo.bat", vbNormalFocus)
' esperar a que se complete el proceso
hProc = OpenProcess(PROCESS_QUERY_INFORMATION, False, hShell)

Do
GetExitCodeProcess hProc, codExit
DoEvents
Loop While codExit = STILL_ACTIVE


MsgBox "El comando ha acabado"

On Error Resume Next
Kill "Archivo.bat"

End Sub
Private Sub Command1_Click()
EjecutarCMDDOS COMANDOS.Text
End Sub

Desconectado Slore

  • *
  • Underc0der
  • Mensajes: 172
  • Actividad:
    0%
  • Reputación 0
  • OrwaySoftware
    • Ver Perfil
    • Email
  • Skype: OrwaySoftware
« Respuesta #72 en: Junio 09, 2012, 06:13:28 am »
Cambiar Iconos del MsgBox
MODULO:

Código:
Option Explicit
Private Const WH_CBT As Long = &H5
Private Const HCBT_ACTIVATE As Long = &H5
Private Const STM_SETICON As Long = &H170
Private Const MODAL_WINDOW_CLASSNAME As String = "#32770"
Private Const SS_ICON As Long = &H3
Private Const WS_VISIBLE As Long = &H10000000
Private Const WS_CHILD As Long = &H40000000
Private Const SWP_NOSIZE As Long = &H1
Private Const SWP_NOZORDER As Long = &H4
Private Const STM_SETIMAGE As Long = &H172
Private Const IMAGE_CURSOR As Long = &H2
Private Declare Function SetWindowsHookEx Lib "user32" Alias "SetWindowsHookExA" (ByVal idHook As Long, ByVal lpfn As Long, ByVal hmod As Long, ByVal dwThreadID As Long) As Long
Private Declare Function CallNextHookEx Lib "user32" (ByVal hHook As Long, ByVal CodeNo As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
Private Declare Function UnhookWindowsHookEx Lib "user32" (ByVal hHook As Long) As Long
Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" (ByVal hwnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
Private Declare Function GetCurrentThreadId Lib "KERNEL32" () As Long
Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal ParenthWnd As Long, ByVal ChildhWnd As Long, ByVal ClassName As String, ByVal Caption As String) As Long
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 Declare Function LoadCursorFromFile Lib "user32" Alias "LoadCursorFromFileA" (ByVal lpFileName As Any) As Long
Private 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
Private Declare Function CreateWindowEx Lib "user32" Alias "CreateWindowExA" (ByVal dwExStyle As Long, ByVal lpClassName As String, ByVal lpWindowName As String, ByVal dwStyle As Long, ByVal x As Long, ByVal y As Long, ByVal nWidth As Long, ByVal nHeight As Long, ByVal hwndParent As Long, ByVal hMenu As Long, ByVal hInstance As Long, lpParam As Any) As Long
Private Declare Function DestroyWindow Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function DestroyCursor Lib "user32" (ByVal hCursor As Long) As Boolean
Private Declare Function IsWindow Lib "user32" (ByVal hwnd As Long) As Long
Public Type ANICURSOR
   m_hCursor As Long
   m_hWnd As Long
End Type
Private pHook As Long
Private phIcon As Long
Private pAniIcon As String
Public Function XMsgBox(ByVal Message As String, _
               Optional ByVal MBoxStyle As VbMsgBoxStyle = vbOKOnly, _
               Optional ByVal Title As String = "", _
               Optional ByVal hIcon As Long = 0&, _
               Optional ByVal AniIcon As String = "") As VbMsgBoxResult
   pHook = SetWindowsHookEx(WH_CBT, _
          AddressOf MsgBoxHookProc, _
                     App.hInstance, _
                 GetCurrentThreadId())
   phIcon = hIcon
   pAniIcon = AniIcon
   If Len(AniIcon) <> 0 Or phIcon <> 0 Then
      MBoxStyle = MBoxStyle And Not (vbCritical)
      MBoxStyle = MBoxStyle And Not (vbExclamation)
      MBoxStyle = MBoxStyle And Not (vbQuestion)
      MBoxStyle = MBoxStyle Or vbInformation
   End If
   XMsgBox = MsgBox(Message, MBoxStyle, Title)
End Function
Private Function MsgBoxHookProc(ByVal CodeNo As Long, _
                                ByVal wParam As Long, _
                                ByVal lParam As Long) As Long
   Dim ClassNameSize As Long
   Dim sClassName As String
   Dim hIconWnd As Long
   Dim M As ANICURSOR
   MsgBoxHookProc = CallNextHookEx(pHook, CodeNo, wParam, lParam)
   If CodeNo = HCBT_ACTIVATE Then
      sClassName = Space$(32)
      ClassNameSize = GetClassName(wParam, sClassName, 32)
      If Left$(sClassName, ClassNameSize) <> MODAL_WINDOW_CLASSNAME Then Exit Function
      If phIcon <> 0 Or Len(pAniIcon) <> 0 Then _
         hIconWnd = FindWindowEx(wParam, 0&, "Static", vbNullString)
      If phIcon <> 0 Then SendMessage hIconWnd, STM_SETICON, phIcon, ByVal 0&
      If Len(pAniIcon) Then AniCreate M, pAniIcon, hIconWnd, 0, 0
      UnhookWindowsHookEx pHook
   End If
End Function
Public Sub AniCreate(ByRef m_AniStuff As ANICURSOR, sAniName As String, hwndParent As Long, x As Long, y As Long)
   AniDestroy m_AniStuff
   With m_AniStuff
      .m_hCursor = LoadCursorFromFile(sAniName)
      If .m_hCursor Then
         .m_hWnd = CreateWindowEx(0, "Static", "", WS_CHILD Or WS_VISIBLE Or SS_ICON, ByVal 20, ByVal 20, 0, 0, hwndParent, 0, App.hInstance, ByVal 0)
         If .m_hWnd Then
            SendMessage .m_hWnd, STM_SETIMAGE, IMAGE_CURSOR, ByVal .m_hCursor
            SetWindowPos .m_hWnd, 0, x, y, 0, 0, SWP_NOZORDER Or SWP_NOSIZE
         Else
            DestroyCursor .m_hCursor
         End If
      End If
   End With
End Sub

Public Sub AniDestroy(ByRef m_AniStuff As ANICURSOR)
   With m_AniStuff
      If .m_hCursor Then _
         If DestroyCursor(.m_hCursor) Then .m_hCursor = 0
      If IsWindow(.m_hWnd) Then _
         If DestroyWindow(.m_hWnd) Then .m_hWnd = 0
   End With
End Sub


FORM:

Código:
Option Explicit
Dim M As ANICURSOR
   
Private Sub CmdAniTest_Click()
   XMsgBox "Icono animado", vbInformation + vbYesNo, "Prueba", , App.Path & "\DINOSAUR.ANI"
End Sub

Private Sub CmdClearFormAni_Click()
   AniDestroy M
   CmdClearFormAni.Enabled = False
End Sub

Private Sub CmdFormAni_Click()
   AniCreate M, App.Path & "\3drbusy10.ani", Me.hwnd, 100, 78
   CmdClearFormAni.Enabled = True
End Sub

Private Sub CmdIconTest_Click()
   XMsgBox "Icono diferente", vbCritical + vbYesNo, "Prueba", PicBullsEye
End Sub ' el PicBullsEye es un picturebox

Desconectado Slore

  • *
  • Underc0der
  • Mensajes: 172
  • Actividad:
    0%
  • Reputación 0
  • OrwaySoftware
    • Ver Perfil
    • Email
  • Skype: OrwaySoftware
« Respuesta #73 en: Junio 09, 2012, 06:13:52 am »
Cambiar texto a botones de MsgBox
Modulo:

Código:
Public hHook As Long
Public Const WH_CALLWNDPROCRET = 12
Public Const GWL_HINSTANCE = (-6)
Private Type tagCWPRETSTRUCT
    lResult As Long
    lParam As Long
    wParam As Long
    message As Long
    hWnd As Long
End Type
Private Const WM_INITDIALOG = &H110
Public Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" _
    (ByVal hWnd As Long, ByVal nIndex As Long) As Long
Public Declare Function GetCurrentThreadId Lib "kernel32" () As Long
Public Declare Function SetWindowsHookEx Lib "user32" Alias "SetWindowsHookExA" _
    (ByVal idHook As Long, ByVal lpfn As Long, _
    ByVal hmod As Long, ByVal dwThreadId As Long) As Long
Private Declare Function UnhookWindowsHookEx Lib "user32" _
    (ByVal hHook As Long) As Long
Private Declare Function CallNextHookEx Lib "user32" _
    (ByVal hHook As Long, ByVal nCode As Long, _
    ByVal wParam As Long, lParam As Any) As Long
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
    (Destination As Any, Source As Any, ByVal Length As Long)
Private Const IDOK = 1
Private Const IDCANCEL = 2
Private Const IDABORT = 3
Private Const IDRETRY = 4
Private Const IDIGNORE = 5
Private Const IDYES = 6
Private Const IDNO = 7
Private Declare Function SetDlgItemText Lib "user32" Alias "SetDlgItemTextA" _
    (ByVal hDlg As Long, ByVal nIDDlgItem As Long, _
    ByVal lpString As String) As Long
Public Function CallWndRetProc(ByVal nCode As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
    Dim lr As Long
    Dim s As tagCWPRETSTRUCT
    lr = CallNextHookEx(hHook, nCode, wParam, lParam)
    If (nCode < 0) Then
        CallWndRetProc = lr
        Exit Function
    End If
    Call CopyMemory(s, ByVal lParam, Len(s))
    If (s.message = WM_INITDIALOG) Then
        Call SetDlgItemText(s.hWnd, IDYES, "Aprobar")
        Call SetDlgItemText(s.hWnd, IDNO, "Rechazar")
        UnhookWindowsHookEx hHook
        lr = 0&
    End If
    CallWndRetProc = lr
End Function


FORM:

Código:
 Dim hInst As Long
    Dim Thread As Long
    Dim i As Long
    hInst = GetWindowLong(Me.hWnd, GWL_HINSTANCE)
    Thread = GetCurrentThreadId()
    hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, AddressOf CallWndRetProc, hInst, Thread)
    i = MsgBox("Presiona en Aprobar o Rechazar.", vbYesNo)
    If i = vbYes Then
        Label1 = "Has presionado en Aprobar"
    ElseIf i = vbNo Then
        Label1 = "Has presionado en Rechazar"
    End If


Desconectado Slore

  • *
  • Underc0der
  • Mensajes: 172
  • Actividad:
    0%
  • Reputación 0
  • OrwaySoftware
    • Ver Perfil
    • Email
  • Skype: OrwaySoftware
« Respuesta #74 en: Junio 09, 2012, 06:14:17 am »
 Otra forma de crear DSN, modificarlo y eliminarlo
Código:
'Declaracion de constantes
Private Const ODBC_ADD_DSN = 1
Private Const ODBC_CONFIG_DSN = 2
Private Const ODBC_REMOVE_DSN = 3
Private Const vbAPINull As Long = 0&
#If Win32 Then
    Private Declare Function SQLConfigDataSource Lib "ODBCCP32.DLL" _
            (ByVal hwndParent As Long, ByVal fRequest As Long, _
             ByVal lpszDriver As String, ByVal lpszAttributes As String) As Long
#Else
    Private Declare Function SQLConfigDataSource Lib "ODBCINST.DLL" _
            (ByVal hwndParent As Integer, ByVal fRequest As Integer, ByVal _
            lpszDriver As String, ByVal lpszAttributes As String) As Integer
#End If


Para crear un DSN :

Código:
#If Win32 Then
    Dim intRet As Long
#Else
    Dim intRet As Integer
#End If
Dim strDriver As String
Dim strAttributes As String

'Driver de SQL Server
strDriver = "SQL Server"
'Driver de MySQL StrDriver = "MySQL ODBC 3.51 Driver"
'Asignamos los parametros separados por null.
strAttributes = "SERVER=SomeServer" & Chr$(0)
strAttributes = strAttributes & "DESCRIPTION=Temp DSN" & Chr$(0)
strAttributes = strAttributes & "DSN=DSN_TEMP" & Chr$(0)
strAttributes = strAttributes & "DATABASE=nombredb" & Chr$(0)
strAttributes = strAttributes & "UID=" & Chr$(0)
strAttributes = strAttributes & "PWD=" & Chr$(0)
'Para mostrar el diálogo usar Form1.Hwnd en vez de vbAPINull.
intRet = SQLConfigDataSource(vbAPINull, ODBC_ADD_DSN, strDriver, strAttributes)
If intRet Then
    MsgBox "DSN Creado"
Else
    MsgBox "Fallo en la creación"
End If


Para Borrarlo:

Código:
#If Win32 Then
    Dim intRet As Long
#Else
    Dim intRet As Integer
#End If
Dim strDriver As String
Dim strAttributes As String
'Driver de SQL Server
strDriver = "SQL Server"
'Drive de MySQL StrDriver = "MySQL ODBC 3.51 Driver"
'Asignamos los parametros separados por null.
strAttributes = "DSN=DSN_TEMP" & Chr$(0)
'Para mostrar el diálogo usar Form1.Hwnd en vez de vbAPINull.
intRet = SQLConfigDataSource(vbAPINull, ODBC_REMOVE_DSN, strDriver, strAttributes)
If intRet Then
    MsgBox "DSN Eliminado"
Else
    MsgBox "Fallo en el borrado"
End If


Para modificarlo:

Código:
#If Win32 Then
    Dim intRet As Long
#Else
    Dim intRet As Integer
#End If
Dim strDriver As String
Dim strAttributes As String

'Driver de SQL Server
strDriver = "SQL Server"
'Drive de MySQL StrDriver = "MySQL ODBC 3.51 Driver"
'Asignamos los parametros separados por null.
strAttributes = "SERVER=OtroSomeServer" & Chr$(0)
strAttributes = strAttributes & "DESCRIPTION=Temp DSN modificado" & Chr$(0)
strAttributes = strAttributes & "DSN=DSN_TEMP" & Chr$(0)
strAttributes = strAttributes & "DATABASE=pubs" & Chr$(0)
strAttributes = strAttributes & "UID=sa" & Chr$(0)
strAttributes = strAttributes & "PWD=" & Chr$(0)

'Para mostrar el diálogo usar Form1.Hwnd en vez de vbAPINull.
intRet = SQLConfigDataSource(vbAPINull, ODBC_CONFIG_DSN, strDriver, strAttributes)
If intRet Then
    MsgBox "DSN Modificado"
Else
    MsgBox "Fallo en la modificacion"
End If


Si el DSN es para access :
- En vez de DATABASE debes usar DBQ y especificar el nombre completo de la base de datos, incluyendo el path y la extension.
- El UID por defecto es admin, aunque en la base de datos este en español y se llame administrador.

Desconectado Slore

  • *
  • Underc0der
  • Mensajes: 172
  • Actividad:
    0%
  • Reputación 0
  • OrwaySoftware
    • Ver Perfil
    • Email
  • Skype: OrwaySoftware
« Respuesta #75 en: Junio 09, 2012, 06:14:52 am »
Convertir un Path de nombre largo a nombre corto
Supongamos que tienen un PATH (ruta de carpeta) larga, como por ejemplo "C:\Archivos de programa\". Y por algun motivo, quieren acortarla, ejemplo "C:\ARCHIV~1\". Entonces creen un modulo y carguen, lo siguiente y utilicen esta funcion.

Código:
'----- Creado por CULD -----
'- Para llamar a esta funcion utilizar:
'Variable = AcortarPath(Ruta)
'- Donde RUTA es la ruta LARGA que se quiere acortar
'- IMPORTANTE: Si o si, la ruta debe existir en la PC, si no existe no puede acortar.

Private Declare Function GetShortPathName Lib "kernel32" Alias "GetShortPathNameA" _
    (ByVal lpszLongPath As String, ByVal lpszShortPath As String, _
    ByVal cchBuffer As Long) As Long

Public Function AcortarPath(Ruta As String) As String
Dim sBuf As String * 260
Dim i As Long

i = GetShortPathName(Ruta, sBuf, Len(sBuf))
AcortarPath = Left$(sBuf, i)
End Function

Desconectado Slore

  • *
  • Underc0der
  • Mensajes: 172
  • Actividad:
    0%
  • Reputación 0
  • OrwaySoftware
    • Ver Perfil
    • Email
  • Skype: OrwaySoftware
« Respuesta #76 en: Junio 09, 2012, 06:15:11 am »
Pasar datos de un campo MEMO a un campo TEXTO en Access
Sabido es que el campo de tipo texto en Access no acepta más de 255 caracteres, de modo que si alguna vez queremos pasar de el contenido de un campo tipo Memo a un campo tipo Texto, nos será imposible.

Aquí les va un pequeño código que trunca la cadena de caracteres en el 250, con lo cual lo demás es posible.

Código:
Dim VCadena As String
Dim VCadenaAcum As String

Private Sub Command1_Click()
With TESTRA.datPrimaryRS
.Recordset.MoveFirst
Do While Not .Recordset.EOF = True
If IsNull(.Recordset!P) = True Then
.Recordset.MoveNext 'Si está vacío, obvia el registro
Else
VCadena = .Recordset!P 'Partimos del campo memo
VCadenaAcum = "" 'Seteamos a "" por el loop
VCadenaAcum = Mid(VCadena, 1, 250) 'Truncando cadena
.Recordset!Sort = VCadenaAcum 'Copiando al campo tipo texto
.Recordset.Update
.Recordset.MoveNext
End If
Loop
End With
End Sub

Desconectado Slore

  • *
  • Underc0der
  • Mensajes: 172
  • Actividad:
    0%
  • Reputación 0
  • OrwaySoftware
    • Ver Perfil
    • Email
  • Skype: OrwaySoftware
« Respuesta #77 en: Junio 09, 2012, 06:15:29 am »
Como crear un capturador de pantalla
Código:
'Capturar la pantalla entera o la ventana activa:

'Añada dos botones y escriba el siguiente código
Private Declare Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)

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

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

Desconectado Slore

  • *
  • Underc0der
  • Mensajes: 172
  • Actividad:
    0%
  • Reputación 0
  • OrwaySoftware
    • Ver Perfil
    • Email
  • Skype: OrwaySoftware
« Respuesta #78 en: Junio 09, 2012, 06:16:31 am »
Como ejecutar un Stored Procedure
Bueno por alli he visto que preguntan como ejecutar o bien como pasarle un parametro aun stored procedure, bien el ejemplo ejecuta y recibe datos de un stored procedure..

teniendo un stored procedure así:

Código:
CREATE PROCEDURE dbo.Proc_revision_reg(@Reg bigint)
AS SELECT     id_registro, cancelado
FROM         dbo.pricipal_registros
WHERE     (cancelado = 0) AND (id_cuenta_registro = @Reg)
GO


solo ejecutamos un codigo así desde visual basic..

Código:
Dim db As ADODB.Connection
Dim DB as ADoDB.connection
Dim Cmd As ADODB.Command
Db2.Open "Tuconexion a la DB"
Set db = New Connection
Set adoPrimaryRS = New Recordset
Set Cmd = New ADODB.Command

    With Cmd
        .ActiveConnection = db
        .CommandText = "NombreProcedimiento"
        .CommandType = adCmdStoredProc
        .Parameters("@REG") = NodeRegistro
         Set adoPrimaryRS = .Execute ' aqui pasa los valores al recordset
    End With

Desconectado Slore

  • *
  • Underc0der
  • Mensajes: 172
  • Actividad:
    0%
  • Reputación 0
  • OrwaySoftware
    • Ver Perfil
    • Email
  • Skype: OrwaySoftware
« Respuesta #79 en: Junio 09, 2012, 06:24:19 am »
Listar Las Fuentes Del Sistema En ComboBox
este ejemplo lista las fuentes del sistema en un combobox y se le puede aplicar multiples usos en un editor de texto por ejemplo:

ingresa solo un combobox en el form1

en un modulo:

Código:
Public Const LF_FACESIZE = 32

Type LOGFONT

lfHeight As Long

lfWidth As Long

lfEscapement As Long

lfOrientation As Long

lfWeight As Long

lfItalic As Byte

lfUnderline As Byte

lfStrikeOut As Byte

lfCharSet As Byte

lfOutPrecision As Byte

lfClipPrecision As Byte

lfQuality As Byte

lfPitchAndFamily As Byte

lfFaceName(LF_FACESIZE) As Byte

End Type

Type NEWTEXTMETRIC

tmHeight As Long

tmAscent As Long

tmDescent As Long

tmInternalLeading As Long

tmExternalLeading As Long

tmAveCharWidth As Long

tmMaxCharWidth As Long

tmWeight As Long

tmOverhang As Long

tmDigitizedAspectX As Long

tmDigitizedAspectY As Long

tmFirstChar As Byte

tmLastChar As Byte

tmDefaultChar As Byte

tmBreakChar As Byte

tmItalic As Byte

tmUnderlined As Byte

tmStruckOut As Byte

tmPitchAndFamily As Byte

tmCharSet As Byte

ntmFlags As Long

ntmSizeEM As Long

ntmCellHeight As Long

ntmAveWidth As Long

End Type
Declare Function EnumFontFamiliesEx Lib "gdi32" Alias "EnumFontFamiliesExA" (ByVal hdc As Long, lpLogFont As LOGFONT, ByVal lpEnumFontProc As Long, ByVal LParam As Long, ByVal dw As Long) As Long
Function EnumFontFamProc(lpNLF As LOGFONT, lpNTM As NEWTEXTMETRIC, ByVaFontType As Long, LParam As Long) As Long
Dim FaceName As String
FaceName = StrConv(lpNLF.lfFaceName, vbUnicode)
Form1.Combo1.AddItem FaceName
EnumFontFamProc = 1
End Function


en el form_load pone:

Código:
Dim LF As LOGFONT
EnumFontFamiliesEx Me.hdc, LF, AddressOf EnumFontFamProc, ByVal 0&, 0


 

¿Te gustó el post? COMPARTILO!