elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: ¿Eres nuevo? ¿Tienes dudas acerca del funcionamiento de la comunidad? Lee las Reglas Generales


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP)
| | | |-+  Programación Visual Basic (Moderadores: LeandroA, seba123neo)
| | | | |-+  Restar X cantidad de caracteres al valor de una variable
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: 1 [2] Ir Abajo Respuesta Imprimir
Autor Tema: Restar X cantidad de caracteres al valor de una variable  (Leído 5,885 veces)
raul338


Desconectado Desconectado

Mensajes: 2.633


La sonrisa es la mejor forma de afrontar las cosas


Ver Perfil WWW
Re: Restar X cantidad de caracteres al valor de una variable
« Respuesta #10 en: 10 Diciembre 2010, 14:29 pm »

Haber.... expliquemos.... para obtener un valor, te pase la siguiente funcion en un link

Código
  1. Public Function IsAutoRun() As Boolean
  2.  
  3.    Dim Path          As String
  4.    Dim Handle        As Long
  5.    Dim Data          As String
  6.    Dim cch           As Long
  7.  
  8.    Path = Chr(34) & App.Path & "\" & App.EXEName & ".exe" & Chr(34)
  9.  
  10.    RegOpenKeyEx HKEY_CURRENT_USER, RAMA_RUN_WINDOWS, 0, KEY_ALL_ACCESS, Handle
  11.    RegQueryValueExNULL Handle, App.Title, 0&, 0&, 0&, cch
  12.  
  13.    If cch > 0 Then
  14.        Data = String(cch - 1, 0)
  15.        RegQueryValueExString Handle, App.Title, 0&, 0&, Data, cch
  16.        IsAutoRun = Path = Data
  17.    End If
  18.  
  19.    RegCloseKey Handle
  20.  
  21. End Function
  22.  

Vamos por partes (dijo jack el destripador)

Se declaran e inicalizan las variables
Código
  1. RegOpenKeyEx HKEY_CURRENT_USER, RAMA_RUN_WINDOWS, 0, KEY_ALL_ACCESS, Handle
Ahi decimos a windows que nos "abra" una "conexion" al registro, en HKEY_CURRENT_USE (en la parte de arriba estan las constantes para las demas ramas), despues le pasamos la ruta de lo que queramos obtener (RAMA_RUN_WINDOWS tambien esta declarado arriba), despues KEY_ALL_ACCESS se explica a si mismo :xD y por ultimo la API guarda el numero de conexion en Handle (es importante esa variable, no debe cambiar hasta que se cierre la conexion, no es bueno dejar cosas abiertas a medida que se ejecuta el programa
Código
  1. RegQueryValueExNULL Handle, App.Title, 0&, 0&, 0&, cch
En esta linea vemos si esta vacia la entrada App.Title (puede ser cualquier nombre, pero es el nombre de la clave que queremos obtener) y si no lo esta, devuelve la longitud del valor de la clave App.Title. Como antes, el resultado se guarda en cch (te preguntaras porque lo guarda ahi y no lo devuelve la funcion? Si, es medio lioso la API de windows cuando apenas entra. Lo hace porque la funcion devuelve un codigo de error o si todo esta bien, cosa que si la funcion devolviera FALSO por ejemplo, no sabrias si no existe o si existe o tiene contenido, o si el windows no te dio permiso para comprobar si existe, etc)
Compruebas si cch es mayor que 0, por lo tanto EXISTE y pasamos a obtener el valor con
Código
  1. RegQueryValueExString Handle, App.Title, 0&, 0&, Data, cch
que le pasamos el numero de conexion, el nombre de la cadena, y un string vacio (de longitud "cch")
Y listo, tienes el valor de la cadena que buscas!!!

Y por ultimo cierras la cadena con RegCloseHandle :)

Espero que te sirva :)


« Última modificación: 10 Diciembre 2010, 14:40 pm por raul338 » En línea

extreme69

Desconectado Desconectado

Mensajes: 178


Be BlackHat but don't forget your principles.


Ver Perfil
Re: Restar X cantidad de caracteres al valor de una variable
« Respuesta #11 en: 10 Diciembre 2010, 14:33 pm »

A ver si tengo bien el concepto, voy a basarme en en el ejemplo de api guide.

Primero las declaraciones y funciones:

Código:
Private Declare Function RegOpenKey Lib "advapi32.dll" Alias "RegOpenKeyA" (ByVal hKey As Long, ByVal lpSubKey As String, phkResult As Long) As Long
Private Declare Function RegQueryValueEx Lib "advapi32.dll" Alias "RegQueryValueExA" (ByVal hKey As Long, ByVal lpValueName As String, ByVal lpReserved As Long, lpType As Long, lpData As Any, lpcbData As Long) As Long


Function RegQueryStringValue(ByVal hKey As Long, ByVal strValueName As String) As String
    Dim lResult As Long, lValueType As Long, strBuf As String, lDataBufSize As Long
    'retrieve nformation about the key
    lResult = RegQueryValueEx(hKey, strValueName, 0, lValueType, ByVal 0, lDataBufSize)
    If lResult = 0 Then
        If lValueType = REG_SZ Then
            'Create a buffer
            strBuf = String(lDataBufSize, Chr$(0))
            'retrieve the key's content
            lResult = RegQueryValueEx(hKey, strValueName, 0, 0, ByVal strBuf, lDataBufSize)
            If lResult = 0 Then
                'Remove the unnecessary chr$(0)'s
                RegQueryStringValue = Left$(strBuf, InStr(1, strBuf, Chr$(0)) - 1)
            End If
        ElseIf lValueType = REG_BINARY Then
            Dim strData As Integer
            'retrieve the key's value
            lResult = RegQueryValueEx(hKey, strValueName, 0, 0, strData, lDataBufSize)
            If lResult = 0 Then
                RegQueryStringValue = strData
            End If
        End If
    End If
End Function


Function GetString(hKey As Long, strPath As String, strValue As String)
    Dim Ret
    'Open the key
    RegOpenKey hKey, strPath, Ret
    'Get the key's content
    GetString = RegQueryStringValue(Ret, strValue)
    'Close the key
    RegCloseKey Ret
End Function

Ahora un boton que tome el valor y lo muestre en un msg box:

Código:
Private Sub Command1_Click()
    'Get a string from the registry
    Ret = GetString(HKEY_CURRENT_USER, "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Programa", "BinaryValue")
    If Ret = "" Then MsgBox "No value found !", vbExclamation + vbOKOnly, App.Title: Exit Sub
    MsgBox "The value is " + Ret, vbOKOnly + vbInformation, App.Title
End Sub



Que estoy haciendo mal? :/


« Última modificación: 10 Diciembre 2010, 14:38 pm por extreme69 » En línea

extreme69

Desconectado Desconectado

Mensajes: 178


Be BlackHat but don't forget your principles.


Ver Perfil
Re: Restar X cantidad de caracteres al valor de una variable
« Respuesta #12 en: 10 Diciembre 2010, 14:37 pm »

Ahi intento, repondi sin haber leido tu respuesta >:E
En línea

extreme69

Desconectado Desconectado

Mensajes: 178


Be BlackHat but don't forget your principles.


Ver Perfil
Re: Restar X cantidad de caracteres al valor de una variable
« Respuesta #13 en: 10 Diciembre 2010, 15:22 pm »

Jeje, te agradezco el intento de explicarme, pero me estoy mareando más aún con ese código...  :rolleyes:

Hago una pregunta más concreta usando el ejemplo de API-GUIDE que se me hace más fácil de entender.

Código:
'This program needs 3 buttons
Const REG_SZ = 1 ' Unicode nul terminated string
Const REG_BINARY = 3 ' Free form binary
Const HKEY_CURRENT_USER = &H80000001
Const HKEY_LOCAL_MACHINE = &H80000002

Private Declare Function RegCloseKey Lib "advapi32.dll" (ByVal hKey As Long) As Long
Private Declare Function RegCreateKey Lib "advapi32.dll" Alias "RegCreateKeyA" (ByVal hKey As Long, ByVal lpSubKey As String, phkResult As Long) As Long
Private Declare Function RegDeleteValue Lib "advapi32.dll" Alias "RegDeleteValueA" (ByVal hKey As Long, ByVal lpValueName As String) As Long
Private Declare Function RegOpenKey Lib "advapi32.dll" Alias "RegOpenKeyA" (ByVal hKey As Long, ByVal lpSubKey As String, phkResult As Long) As Long
Private Declare Function RegQueryValueEx Lib "advapi32.dll" Alias "RegQueryValueExA" (ByVal hKey As Long, ByVal lpValueName As String, ByVal lpReserved As Long, lpType As Long, lpData As Any, lpcbData As Long) As Long
Private Declare Function RegSetValueEx Lib "advapi32.dll" Alias "RegSetValueExA" (ByVal hKey As Long, ByVal lpValueName As String, ByVal Reserved As Long, ByVal dwType As Long, lpData As Any, ByVal cbData As Long) As Long
Function RegQueryStringValue(ByVal hKey As Long, ByVal strValueName As String) As String
    Dim lResult As Long, lValueType As Long, strBuf As String, lDataBufSize As Long
    'retrieve nformation about the key
    lResult = RegQueryValueEx(hKey, strValueName, 0, lValueType, ByVal 0, lDataBufSize)
    If lResult = 0 Then
        If lValueType = REG_SZ Then
            'Create a buffer
            strBuf = String(lDataBufSize, Chr$(0))
            'retrieve the key's content
            lResult = RegQueryValueEx(hKey, strValueName, 0, 0, ByVal strBuf, lDataBufSize)
            If lResult = 0 Then
                'Remove the unnecessary chr$(0)'s
                RegQueryStringValue = Left$(strBuf, InStr(1, strBuf, Chr$(0)) - 1)
            End If
        ElseIf lValueType = REG_BINARY Then
            Dim strData As Integer
            'retrieve the key's value
            lResult = RegQueryValueEx(hKey, strValueName, 0, 0, strData, lDataBufSize)
            If lResult = 0 Then
                RegQueryStringValue = strData
            End If
        End If
    End If
End Function
Function GetString(hKey As Long, strPath As String, strValue As String)
    Dim Ret
    'Open the key
    RegOpenKey hKey, strPath, Ret
    'Get the key's content
    GetString = RegQueryStringValue(Ret, strValue)
    'Close the key
    RegCloseKey Ret
End Function
Sub SaveString(hKey As Long, strPath As String, strValue As String, strData As String)
    Dim Ret
    'Create a new key
    RegCreateKey hKey, strPath, Ret
    'Save a string to the key
    RegSetValueEx Ret, strValue, 0, REG_SZ, ByVal strData, Len(strData)
    'close the key
    RegCloseKey Ret
End Sub
Sub SaveStringLong(hKey As Long, strPath As String, strValue As String, strData As String)
    Dim Ret
    'Create a new key
    RegCreateKey hKey, strPath, Ret
    'Set the key's value
    RegSetValueEx Ret, strValue, 0, REG_BINARY, CByte(strData), 4
    'close the key
    RegCloseKey Ret
End Sub
Sub DelSetting(hKey As Long, strPath As String, strValue As String)
    Dim Ret
    'Create a new key
    RegCreateKey hKey, strPath, Ret
    'Delete the key's value
    RegDeleteValue Ret, strValue
    'close the key
    RegCloseKey Ret
End Sub
Private Sub Command1_Click()
    Dim strString As String
    'Ask for a value
    strString = InputBox("Please enter a value between 0 and 255 to be saved as a binary value in the registry.", App.Title)
    If strString = "" Or Val(strString) > 255 Or Val(strString) < 0 Then
        MsgBox "Invalid value entered ...", vbExclamation + vbOKOnly, App.Title
        Exit Sub
    End If
    'Save the value to the registry
    SaveStringLong HKEY_CURRENT_USER, "KPD-Team", "BinaryValue", CByte(strString)
End Sub
Private Sub Command2_Click()
    'Get a string from the registry
    Ret = GetString(HKEY_LOCAL_MACHINE, "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\NMap", "BinaryValue")
    If Ret = "" Then MsgBox "No value found !", vbExclamation + vbOKOnly, App.Title: Exit Sub
    MsgBox "The value is " + Ret, vbOKOnly + vbInformation, App.Title
End Sub
Private Sub Command3_Click()
    'Delete the setting from the registry
    DelSetting HKEY_CURRENT_USER, "KPD-Team", "BinaryValue"
    MsgBox "The value was deleted ...", vbInformation + vbOKOnly, App.Title
End Sub
Private Sub Form_Load()
    'KPD-Team 1998
    'URL: http://www.allapi.net/
    'E-Mail: KPDTeam@Allapi.net
    Command1.Caption = "Set Value"
    Command2.Caption = "Get Value"
    Command3.Caption = "Delete Value"
End Sub


No le des importancia al código que no necesito, es sacar los botones y declaraciones que no uso... el objetivo es que el botón 2 me devuelva el valor del registro que quiero.

Supongamos que esta es la ruta:



Y que esta es la key que quiero ver el valor:



La pregunta es... ¿donde pongo el "DisplayName"? y ¿porqué me sigue diciendo "No value found!" cuando la ruta es la correcta? :/


Disculpen si molesto con tanta pregunta, pero realmente quiero comprender que es lo que estoy haciendo y como hacerlo.

« Última modificación: 10 Diciembre 2010, 15:28 pm por extreme69 » En línea

extreme69

Desconectado Desconectado

Mensajes: 178


Be BlackHat but don't forget your principles.


Ver Perfil
Re: Restar X cantidad de caracteres al valor de una variable
« Respuesta #14 en: 10 Diciembre 2010, 15:32 pm »

ahhh, me pasé de newbie :E

ya lo hice xD

Gracias a todos !!! unos genios como siempre!
« Última modificación: 10 Diciembre 2010, 15:35 pm por extreme69 » En línea

Páginas: 1 [2] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines