Solved

Set Value in Registry : RegSetValueEx  API...

Posted on 1998-08-13
4
683 Views
Last Modified: 2012-05-04
I need to access to the Windows Registry sush as set it value or get value from it. So, this is my code:

   Dim m_hKey as long
   Dim data as String
   data = "Hello, World"

   RegCreateKey HKEY_LOCAL_MACHINE, "Software\JOM", m_hKey
   RegSetValue m_hKey, "MyWord", 0, REG_SZ, data, Len(data)

    the result is, the subkey JOM was created and Value name MyWord was created ,too but its value was not "Hello, World", there are 2-3 characters.

    How can I do.?
0
Comment
Question by:jom080298
  • 2
  • 2
4 Comments
 
LVL 14

Accepted Solution

by:
waty earned 100 total points
ID: 1468695
Here is my module used to handle the registry.

Use this one and tell me the result.

Option Explicit

'---------------------------------------------------------------
'-Registry API Declarations...
'---------------------------------------------------------------
Declare Function RegCloseKey Lib "advapi32" (ByVal hKey As Long) As Long
Declare Function RegCreateKeyEx Lib "advapi32" Alias "RegCreateKeyExA" (ByVal hKey As Long, ByVal lpSubKey As String, ByVal Reserved As Long, ByVal lpClass As String, ByVal dwOptions As Long, ByVal samDesired As Long, ByRef lpSecurityAttributes As SECURITY_ATTRIBUTES, ByRef phkResult As Long, ByRef lpdwDisposition As Long) As Long
Declare Function RegDeleteKey Lib "advapi32" Alias "RegDeleteKeyA" (ByVal hKey As Long, ByVal lpSubKey As String) As Long
Declare Function RegOpenKeyEx Lib "advapi32" Alias "RegOpenKeyExA" (ByVal hKey As Long, ByVal lpSubKey As String, ByVal ulOptions As Long, ByVal samDesired As Long, ByRef phkResult As Long) As Long
Declare Function RegQueryValueEx Lib "advapi32" Alias "RegQueryValueExA" (ByVal hKey As Long, ByVal lpValueName As String, ByVal lpReserved As Long, ByRef lpType As Long, ByVal lpData As String, ByRef lpcbData As Long) As Long
Declare Function RegSetValueEx Lib "advapi32" Alias "RegSetValueExA" (ByVal hKey As Long, ByVal lpValueName As String, ByVal Reserved As Long, ByVal dwType As Long, ByVal lpData As String, ByVal cbData As Long) As Long

' Reg Data Types...
Global Const REG_NONE = 0                       ' No value type
Global Const REG_SZ = 1                         ' Unicode nul terminated string
Global Const REG_EXPAND_SZ = 2                  ' Unicode nul terminated string
Global Const REG_BINARY = 3                     ' Free form binary
Global Const REG_DWORD = 4                      ' 32-bit number
Global Const REG_DWORD_LITTLE_ENDIAN = 4        ' 32-bit number (same as REG_DWORD)
Global Const REG_DWORD_BIG_ENDIAN = 5           ' 32-bit number
Global Const REG_LINK = 6                       ' Symbolic Link (unicode)
Global Const REG_MULTI_SZ = 7                   ' Multiple Unicode strings
Global Const REG_RESOURCE_LIST = 8              ' Resource list in the resource map
Global Const REG_FULL_RESOURCE_DESCRIPTOR = 9   ' Resource list in the hardware description
Global Const REG_RESOURCE_REQUIREMENTS_LIST = 10

' Reg Create Type Values...
Global Const REG_OPTION_RESERVED = 0           ' Parameter is reserved
Global Const REG_OPTION_NON_VOLATILE = 0       ' Key is preserved when system is rebooted
Global Const REG_OPTION_VOLATILE = 1           ' Key is not preserved when system is rebooted
Global Const REG_OPTION_CREATE_LINK = 2        ' Created key is a symbolic link
Global Const REG_OPTION_BACKUP_RESTORE = 4     ' open for backup or restore

' Reg Key Security Options...
Global Const READ_CONTROL = &H20000
Global Const KEY_QUERY_VALUE = &H1
Global Const KEY_SET_VALUE = &H2
Global Const KEY_CREATE_SUB_KEY = &H4
Global Const KEY_ENUMERATE_SUB_KEYS = &H8
Global Const KEY_NOTIFY = &H10
Global Const KEY_CREATE_LINK = &H20
Global Const KEY_READ = KEY_QUERY_VALUE + KEY_ENUMERATE_SUB_KEYS + KEY_NOTIFY + READ_CONTROL
Global Const KEY_WRITE = KEY_SET_VALUE + KEY_CREATE_SUB_KEY + READ_CONTROL
Global Const KEY_EXECUTE = KEY_READ
Global Const KEY_ALL_ACCESS = KEY_QUERY_VALUE + KEY_SET_VALUE + _
                              KEY_CREATE_SUB_KEY + KEY_ENUMERATE_SUB_KEYS _
                            + KEY_NOTIFY + KEY_CREATE_LINK + READ_CONTROL
                     
' Reg Key ROOT Types...
Global Const HKEY_CLASSES_ROOT = &H80000000
Global Const HKEY_CURRENT_USER = &H80000001
Global Const HKEY_LOCAL_MACHINE = &H80000002
Global Const HKEY_USERS = &H80000003
Global Const HKEY_PERFORMANCE_DATA = &H80000004

' Return Value...
Global Const ERROR_SUCCESS = 0

'---------------------------------------------------------------
'- Registry Security Attributes TYPE...
'---------------------------------------------------------------
Type SECURITY_ATTRIBUTES
        nLength As Long
        lpSecurityDescriptor As Long
        bInheritHandle As Boolean
End Type

Global Const MAX_BUFFER_LEN = 255                       ' Maximum Size Of A String Buffer (Used In ODBC API Calls)
'
'------------------------------------------------------------
Public Function DeleteKey(KeyRoot As Long, KeyName As String) As Boolean
'------------------------------------------------------------
    '<<< Win95 - will delete a Registry Key and all of it's descendants.        >>>
    '<<< WinNT - will delete a Registry Key ONLY if NO descendants are present. >>>
    Dim rc As Long                                  ' Return Code
'------------------------------------------------------------
    DeleteKey = False                               ' Set Return Code To Fail...
       
    rc = RegDeleteKey(KeyRoot, KeyName)             ' Delete Key From KeyRoot {HKEY_LOCAL_MACHINE...}
    If (rc = ERROR_SUCCESS) Then                    ' If Success Then Return Success
        DeleteKey = True                            ' Return Success
    End If
'------------------------------------------------------------
End Function
'------------------------------------------------------------

'------------------------------------------------------------
Public Function GetKeyValue(KeyRoot As Long, KeyName As String, SubKeyRef As String, ByRef KeyVal As String) As Boolean
'------------------------------------------------------------
    Dim i As Long                                           ' Loop Counter
    Dim rc As Long                                          ' Return Code
    Dim hKey As Long                                        ' Handle To An Open Registry Key
    Dim hDepth As Long                                      '
    Dim KeyValType As Long                                  ' Data Type Of A Registry Key
    Dim tmpVal As String                                    ' Tempory Storage For A Registry Key Value
    Dim KeyValSize As Long                                  ' Size Of Registry Key Variable
'------------------------------------------------------------
    ' Open RegKey Under KeyRoot {HKEY_LOCAL_MACHINE...}
    '------------------------------------------------------------
    rc = RegOpenKeyEx(KeyRoot, KeyName, 0, KEY_ALL_ACCESS, hKey) ' Open Registry Key
   
    If (rc <> ERROR_SUCCESS) Then GoTo GetKeyError          ' Handle Error...
   
    '------------------------------------------------------------
    ' Query Reg Key Value...
    ' Get Key Size & Type Information...
    '------------------------------------------------------------
    rc = RegQueryValueEx(hKey, SubKeyRef, 0, _
                         KeyValType, tmpVal, KeyValSize)    ' Search Get Registry Key Value

    '------------------------------------------------------------
    ' Allocate Space For tmpVal, Call Will Fail If tmpVal Is Empty.
    '------------------------------------------------------------
    If ((rc = ERROR_SUCCESS) And (KeyValSize > 0)) Then         ' If Value Exists Then...
        tmpVal = Space(KeyValSize - 1)                          ' Pad String w/SizeOf(KeyValue) Spaces
    Else
        tmpVal = Space(1)                                       ' Pad String w/Space
    End If
   
    '------------------------------------------------------------
    ' Retrieve Registry Key Value...
    '------------------------------------------------------------
    rc = RegQueryValueEx(hKey, SubKeyRef, 0, _
                         KeyValType, tmpVal, LenB(tmpVal))      ' Get/Create Key Value
                       
    If (rc <> ERROR_SUCCESS) Then GoTo GetKeyError              ' Handle Errors
   
    '------------------------------------------------------------
    ' Determine Key Value Type For Conversion...
    '------------------------------------------------------------
    Select Case KeyValType                              ' Search Data Types...
    Case REG_SZ                                         ' String Registry Key Data Type
        KeyVal = tmpVal                                 ' Copy String Value
    Case REG_DWORD                                      ' Double Word Registry Key Data Type
        For i = Len(tmpVal) To 1 Step -1                ' Convert Each Bit
            KeyVal = KeyVal + Hex(Asc(Mid(tmpVal, i, 1))) ' Build Value Char. By Char.
        Next
        KeyVal = Format$("&h" + KeyVal)                 ' Convert Double Word To String
    End Select
   
    GetKeyValue = True                                  ' Return Success
    rc = RegCloseKey(hKey)                              ' Close Registry Key
    Exit Function                                       ' Exit
   
'------------------------------------------------------------
GetKeyError:    ' Cleanup After An Error Has Occured...
'------------------------------------------------------------
    KeyVal = ""                                         ' Set Return Val To Empty String
    GetKeyValue = False                                 ' Return Failure
    rc = RegCloseKey(hKey)                              ' Close Registry Key
'------------------------------------------------------------
End Function
'------------------------------------------------------------


'------------------------------------------------------------
Public Function UpdateKey(KeyRoot As Long, KeyName As String, SubKeyName As String, SubKeyValue As String) As Boolean
'------------------------------------------------------------
    Dim rc As Long                                      ' Return Code
    Dim hKey As Long                                    ' Handle To A Registry Key
    Dim hDepth As Long                                  '
    Dim lpAttr As SECURITY_ATTRIBUTES                   ' Registry Security Type
'------------------------------------------------------------
    lpAttr.nLength = 50                                 ' Set Security Attributes To Defaults...
    lpAttr.lpSecurityDescriptor = 0                     ' ...
    lpAttr.bInheritHandle = True                        ' ...

    '------------------------------------------------------------
    '- Create/Open Registry Key...
    '------------------------------------------------------------
    rc = RegCreateKeyEx(KeyRoot, KeyName, _
                        0, REG_SZ, _
                        REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, lpAttr, _
                        hKey, hDepth)                   ' Create/Open //KeyRoot//KeyName
   
    If (rc <> ERROR_SUCCESS) Then GoTo CreateKeyError   ' Handle Errors...
   
    '------------------------------------------------------------
    '- Create/Modify Key Value...
    '------------------------------------------------------------
    If (SubKeyValue = "") Then SubKeyValue = " "        ' A Space Is Needed For RegSetValueEx() To Work...
   
    rc = RegSetValueEx(hKey, SubKeyName, _
                       0, REG_SZ, _
                       SubKeyValue, LenB(SubKeyValue))  ' Create/Modify Key Value

    If (rc <> ERROR_SUCCESS) Then GoTo CreateKeyError   ' Handle Error
    '------------------------------------------------------------
    '- Close Registry Key...
    '------------------------------------------------------------
    rc = RegCloseKey(hKey)                              ' Close Key
   
    UpdateKey = True                                    ' Return Success
    Exit Function                                       ' Exit
'------------------------------------------------------------
CreateKeyError:
'------------------------------------------------------------
    UpdateKey = False                                   ' Set Error Return Code
    rc = RegCloseKey(hKey)                              ' Attempt To Close Key
'------------------------------------------------------------
End Function
'------------------------------------------------------------

0
 

Author Comment

by:jom080298
ID: 1468696
Thank you very much.
0
 

Author Comment

by:jom080298
ID: 1468697
To Waty,
      now I can set the value the the registry but it can set just the string value, can not set the integer or long, because you change the declare function of RegSetValueEx on the lpData parameter to ByVal lpData as String. So, please help me again to can set the value both String and Int or Long.

Waiting for your help.
0
 
LVL 14

Expert Comment

by:waty
ID: 1468698
You can add those declaration and modify the class I gave you.

Private Declare Function RegSetValueExLong Lib "advapi32" Alias "RegSetValueExA" _
  (ByVal hKey As Long, ByVal lpValueName As String, ByVal Reserved As Long, _
   ByVal dwType As Long, szData As Long, ByVal cbData As Long) As Long
Private Declare Function RegSetValueExByte Lib "advapi32" Alias "RegSetValueExA" _
  (ByVal hKey As Long, ByVal lpValueName As String, ByVal Reserved As Long, _
   ByVal dwType As Long, szData As Byte, ByVal cbData As Long) As Long



0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Article by: Martin
Here are a few simple, working, games that you can use as-is or as the basis for your own games. Tic-Tac-Toe This is one of the simplest of all games.   The game allows for a choice of who goes first and keeps track of the number of wins for…
Background What I'm presenting in this article is the result of 2 conditions in my work area: We have a SQL Server production environment but no development or test environment; andWe have an MS Access front end using tables in SQL Server but we a…
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now