VB6•Create the Windows Registry Key

Listing 1. Create the Windows Registry key for the DSN connection using the RegCreateKey, RegSetValueEx, and RegCloseKey API functions. Place this code in the click event for the command button cmdCreateRegKey.

Private Sub cmdCreateRegKey _Click()
   Dim sDSNName As String
   Dim sDatabaseName As String
   Dim sDescription As String
   Dim sDriverPath As String

   Dim sLastUser As String
   Dim sRegional As String
   Dim sServer As String
   Dim sDriveLetter As String
   Dim sPassword As String
   Dim lRetVal As Long
   Dim hKeyHandle As Long
   Dim sPath As String
   Dim sDriveLetter

   10   sDriveLetter="C:\"          
   20   sDSNName = "MyDSNName" 
   30   sDescription = "SQL Server Database"
   40   sDatabaseName = "MyDatabase"
   50   sDriverPath = sDriveLetter & _
      "WINNT\SYSTEM32\SQLSRV32.dll"
   60   sLastUser = "sa"
   70   sServer = "MyServerName"

   '/* create the  new key */
   '/* HKEY_LOCAL_MACHINE is the default location for DSN 
   '/* files. Alternative location would be HKEY_CURRENT_USER

80   lRetVal = RegCreateKey(HKEY_LOCAL_MACHINE, _
     "SOFTWARE\ODBC\ODBC.INI\" & _
     sDSNName,  hKeyHandle)
      'set the values for the new key:
90   lRetVal = RegSetValueEx(hKeyHandle, "Database", 0&, _
     REG_SZ, ByVal sDatabaseName, Len(sDatabaseName))
100   lRetVal = RegSetValueEx(hKeyHandle, "Description", 0&, _
     REG_SZ, ByVal sDescription, Len(sDescription))
110   lRetVal = RegSetValueEx(hKeyHandle, "Driver", 0&, _
     REG_SZ, ByVal sDriverPath, Len(sDriverPath))
120   lRetVal = RegSetValueEx(hKeyHandle, "LastUser", 0&, _
     REG_SZ, ByVal sLastUser, Len(sLastUser))
130   lRetVal = RegSetValueEx(hKeyHandle, "Server", 0&, _
     REG_SZ, ByVal sServer, Len(sServer))
      	'/* close the key */
140   lRetVal = RegCloseKey (hKeyHandle)
      	'/* open ODBC Data Sources Key to list the new DSN in 
      	'/* the ODBC Manager */
150   lRetVal = RegCreateKey(HKEY_CURRENT_USER, _
      "SOFTWARE\ODBC\ODBC.INI\ODBC Data Sources", hKeyHandle)
160   lRetVal = RegSetValueEx(hKeyHandle, "SQL Server", 0&, _
      REG_SZ, ByVal sDSNName, Len(sDSNName))
      	'/* close the key */
170   lRetVal = RegCloseKey(hKeyHandle)

End Sub