[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

Startup Reg.

Posted on 2003-11-06
5
Medium Priority
?
720 Views
Last Modified: 2010-07-27
I need to make my program add it self to startup, not startup folder but something in the Reg. I have no clue, I know there is a code to add the app to reg startup...
And if anybody gave me the code, will I get any errors after lanching the program the second time? Because the first time it will add it self to reg and the second time it will overright it self???
Can anybody help
0
Comment
Question by:deathman5
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
5 Comments
 
LVL 17

Expert Comment

by:zzzzzooc
ID: 9694034
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

Create a value in that key. Name can be anything and value is the location of your program. It doesn't matter much if it's overwritten. It's even better for such, in case the location of the program changes.

You can use a class module to easily do what you want:

http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=28518&lngWId=1
0
 

Author Comment

by:deathman5
ID: 9694790
well... how to add a value in the key?
I thought this might work:

Call SaveSetting("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion", "\Run", "TESTING", Text1.Text)

but Im having an error, and when I searched for a code, I found this:

  Private Const cPGM = "C:\VB Forum\startup\TestStartup.exe"

   Dim oShell As IWshShell_Class
   Set oShell = New IWshShell_Class
   oShell.RegWrite "HKLM\Software\Microsoft\Windows\CurrentVersion\Run\MyVBApp", _
                   cPGM, "REG_SZ"

but Im also getting an error on  As IWshShell_Class
"user defined-type not defined"
any help?
0
 
LVL 5

Assisted Solution

by:fantasy1001
fantasy1001 earned 60 total points
ID: 9699213
Step:
Add a reference to "Registry Access Function" by menu->Project->Reference

then:
Private Sub Command1_Click()
    Dim objReg As Registry
    Set objReg = New Registry
    objReg.UpdateKey HKEY_LOCAL_MACHINE, "SOFTWARE\Microsoft\Windows\CurrentVersion\run", "test", "value is here"
End Sub

~ fantasy ~
0
 
LVL 1

Accepted Solution

by:
KeyPakt earned 90 total points
ID: 9699964
Call SaveSettings does not work because that registry function saves info in the Visual Basic folder of the windows registry. If you want to save window size and stuff like that the SaveSettings works nice. But in your case you want to have your application to start when windows start. The code bellow will let you do pretty much anything to the windows registry. The code is based on Win32Api so you do not need to add any Refrence. Just paste the code in a Module and use the functions.

//Code starts here
Option Explicit

Public bteAutoStart As Byte

'Check if registrykey is found
Private Declare Function RegOpenKeyEx Lib "advapi32.dll" Alias "RegOpenKeyExA" _
    (ByVal hKey As Long, ByVal lpSubKey As String, ByVal ulOptions As Long, _
    ByVal samDesired As Long, phkResult As Long) As Long

Private Declare Function RegCreateKeyEx Lib "advapi32.dll" Alias _
    "RegCreateKeyExA" (ByVal hKey As Long, ByVal lpSubKey As String, _
    ByVal Reserved As Long, ByVal lpClass As Long, ByVal dwOptions As Long, _
    ByVal samDesired As Long, ByVal lpSecurityAttributes As Long, _
    phkResult As Long, lpdwDisposition As Long) As Long

Private Declare Function RegCloseKey Lib "advapi32.dll" (ByVal hKey As Long) As Long

Private Declare Function RegDeleteKey Lib "advapi32.dll" Alias "RegDeleteKeyA" _
    (ByVal hKey As Long, ByVal lpSubKey As String) 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

Private Declare Function RegDeleteValue Lib "advapi32.dll" Alias _
    "RegDeleteValueA" (ByVal hKey As Long, ByVal lpValueName As String) 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 Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (dest As _
    Any, source As Any, ByVal numBytes As Long)

Const KEY_READ = &H20019  '((READ_CONTROL Or KEY_QUERY_VALUE Or
                          'KEY_ENUMERATE_SUB_KEYS Or KEY_NOTIFY) And (Not
                          'SYNCHRONIZE))
Const REG_OPENED_EXISTING_KEY = &H2

Const KEY_WRITE = &H20006  '((STANDARD_RIGHTS_WRITE Or KEY_SET_VALUE Or
                           ' KEY_CREATE_SUB_KEY) And (Not SYNCHRONIZE))
Const REG_SZ = 1
Const REG_EXPAND_SZ = 2
Const REG_BINARY = 3
Const REG_DWORD = 4
Const REG_MULTI_SZ = 7
Const ERROR_MORE_DATA = 234

' Reg Key ROOT Types...
Const HKEY_CLASSES_ROOT = &H80000000
Const HKEY_CURRENT_USER = &H80000001
Const HKEY_LOCAL_MACHINE = &H80000002
Const HKEY_USERS = &H80000003
Const HKEY_PERFORMANCE_DATA = &H80000004

'Reg KeyPath
Const strRegRunPath As String = "SOFTWARE\Microsoft\Windows\CurrentVersion\Run"

' Return Value...
Const ERROR_NONE = 0
Const ERROR_BADKEY = 2
Const ERROR_ACCESS_DENIED = 8
Const ERROR_SUCCESS = 0

'------------------------------------------------------------------------------------
'Return True if a Registry key exists
Function CheckRegistryKey(ByVal hKey As Long, ByVal KeyName As String) As Boolean
Dim Handle As Long
'Try to open the key
If RegOpenKeyEx(hKey, KeyName, 0, KEY_READ, Handle) = 0 Then
    'The key exists
    CheckRegistryKey = True
    'Close it before exiting
    RegCloseKey Handle
End If
End Function

'------------------------------------------------------------------------------------
'Create a registry key, then close it
'Returns True if the key already existed, False if it was created
Function CreateRegistryKey(ByVal hKey As Long, ByVal KeyName As String) As Boolean
Dim Handle As Long, Disposition As Long

If RegCreateKeyEx(hKey, KeyName, 0, 0, 0, 0, 0, Handle, Disposition) Then
    Err.Raise 1001, , "Unable to create the registry key"
Else
    ' Return True if the key already existed.
    CreateRegistryKey = (Disposition = REG_OPENED_EXISTING_KEY)
    ' Close the key.
    RegCloseKey Handle
End If
End Function

'------------------------------------------------------------------------------------
'Delete a registry key
'Under Windows NT it doesn't work if the key contains subkeys
Sub DeleteRegistryKey(ByVal hKey As Long, ByVal KeyName As String)
RegDeleteKey hKey, KeyName
End Sub

'------------------------------------------------------------------------------------
' Write or Create a Registry value
' returns True if successful
' Use KeyName = "" for the default value
' Value can be an integer value (REG_DWORD), a string (REG_SZ)
' or an array of binary (REG_BINARY). Raises an error otherwise.
Function SetRegistryValue(ByVal hKey As Long, ByVal KeyName As String, _
    ByVal ValueName As String, Value As Variant) As Boolean
Dim Handle As Long
Dim lngValue As Long
Dim strValue As String
Dim binValue() As Byte
Dim Length As Long
Dim retVal As Long

' Open the key, exit if not found
If RegOpenKeyEx(hKey, KeyName, 0, KEY_WRITE, Handle) Then
    Exit Function
End If

' three cases, according to the data type in Value
Select Case VarType(Value)
    Case vbInteger, vbLong
        lngValue = Value
        retVal = RegSetValueEx(Handle, ValueName, 0, REG_DWORD, lngValue, 4)
    Case vbString
        strValue = Value
        retVal = RegSetValueEx(Handle, ValueName, 0, REG_SZ, ByVal strValue, Len(strValue))
    Case vbArray + vbByte
        binValue = Value
        Length = UBound(binValue) - LBound(binValue) + 1
        retVal = RegSetValueEx(Handle, ValueName, 0, REG_BINARY, binValue(LBound(binValue)), Length)
    Case Else
        RegCloseKey Handle
        Err.Raise 1001, , "Unsupported value type"
End Select

'Close the key and signal success
RegCloseKey Handle
'signal success if the value was written correctly
SetRegistryValue = (retVal = 0)
End Function

'------------------------------------------------------------------------------------
'Delete a registry value
'Return True if successful, False if the value hasn't been found
Function DeleteRegistryValue(ByVal hKey As Long, ByVal KeyName As String, ByVal ValueName As String) As Boolean
Dim Handle As Long

'Open the key, exit if not found
If RegOpenKeyEx(hKey, KeyName, 0, KEY_WRITE, Handle) Then Exit Function

'Delete the value (returns 0 if success)
DeleteRegistryValue = (RegDeleteValue(Handle, ValueName) = 0)
'Close the handle
RegCloseKey Handle
End Function

'------------------------------------------------------------------------------------
'Read a Registry value
'Use KeyName = "" for the default value
'If the value isn't there, it returns the DefaultValue
'argument, or Empty if the argument has been omitted
'Supports DWORD, REG_SZ, REG_EXPAND_SZ, REG_BINARY and REG_MULTI_SZ
'REG_MULTI_SZ values are returned as a null-delimited stream of strings
'(VB6 users can use SPlit to convert to an array of string)
Function GetRegistryValue(ByVal hKey As Long, ByVal KeyName As String, _
    ByVal ValueName As String, Optional DefaultValue As Variant) As Variant
Dim Handle As Long
Dim resLong As Long
Dim resString As String
Dim resBinary() As Byte
Dim Length As Long
Dim retVal As Long
Dim valueType As Long

'Prepare the default result. A function returning one of to results
GetRegistryValue = IIf(IsMissing(DefaultValue), Empty, DefaultValue)

'Open the key, exit if not found.
If RegOpenKeyEx(hKey, KeyName, 0, KEY_READ, Handle) Then
    Exit Function
End If

'Prepare a 1K receiving resBinary
Length = 1024
ReDim resBinary(0 To Length - 1) As Byte

'Read the registry key
retVal = RegQueryValueEx(Handle, ValueName, 0, valueType, resBinary(0), Length)

'If resBinary was too small, try again
If retVal = ERROR_MORE_DATA Then
    'Enlarge the resBinary, and read the value again
    ReDim resBinary(0 To Length - 1) As Byte
    retVal = RegQueryValueEx(Handle, ValueName, 0, valueType, resBinary(0), Length)
End If

'Return a value corresponding to the value type
Select Case valueType
    Case REG_DWORD
        CopyMemory resLong, resBinary(0), 4
        GetRegistryValue = resLong
    Case REG_SZ, REG_EXPAND_SZ
        'Copy everything but the trailing null char
        resString = Space$(Length - 1)
        CopyMemory ByVal resString, resBinary(0), Length - 1
        GetRegistryValue = resString
    Case REG_BINARY
        'Resize the result resBinary
        If Length <> UBound(resBinary) + 1 Then
            ReDim Preserve resBinary(0 To Length - 1) As Byte
        End If
        GetRegistryValue = resBinary()
    Case REG_MULTI_SZ
        'Copy everything but the 2 trailing null chars
        resString = Space$(Length - 2)
        CopyMemory ByVal resString, resBinary(0), Length - 2
        GetRegistryValue = resString
    Case Else
        RegCloseKey Handle
        GetRegistryValue = "NoReg"
        Exit Function
        'Err.Raise 1001, , "Unsupported value type"
End Select

'Close the registry key
RegCloseKey Handle
End Function

'------------------------------------------------------------------------------------
'Bellow you'll find all functions and subs that the program calls to connect to the registry

'If Sub is called with true then it´s a check when program starts else it´s a program call
Sub GetRegVal()
Dim resGetRegVal As Variant

resGetRegVal = GetRegistryValue(HKEY_LOCAL_MACHINE, strRegRunPath, "Remember", vbNullChar)

If resGetRegVal = "NoReg" Then
    If MsgBox("Do you want this program to Auto Start with Windows?", vbYesNo, "Auto Start?") = vbYes Then
        If SetRegistryValue(HKEY_LOCAL_MACHINE, strRegRunPath, "Remember", App.Path & "\Remember.exe") = True Then
            bteAutoStart = 1
        Else
            MsgBox "Error while writing value name to the registry!"
        End If
    Else
        If SetRegistryValue(HKEY_LOCAL_MACHINE, strRegRunPath, "Remember", vbNullChar) = True Then
            bteAutoStart = 0
        Else
            MsgBox "Error while writing value name to the registry!"
        End If
    End If
ElseIf resGetRegVal = "" Then
    bteAutoStart = 0
Else
    bteAutoStart = 1
End If
End Sub

Sub WriteRegVal(mnuChecked As Boolean)
If mnuChecked = True Then
    If SetRegistryValue(HKEY_LOCAL_MACHINE, strRegRunPath, "Remember", App.Path & "\Remember.exe") = False Then
        MsgBox "Error while writing value name to the registry!"
        bteAutoStart = 0
    End If
Else
    If SetRegistryValue(HKEY_LOCAL_MACHINE, strRegRunPath, "Remember", vbNullChar) = False Then
        MsgBox "Error while writing value name to the registry!"
    End If
End If
End Sub
0
 

Author Comment

by:deathman5
ID: 9700337
thx alot everybody, but I got the answer yesterday from pscode.com thx anyway, I'll give points to all :)
0

Featured Post

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Have you ever wanted to restrict the users input in a textbox to numbers, and while doing that make sure that they can't 'cheat' by pasting in non-numeric text? Of course you can do that with code you write yourself but it's tedious and error-prone …
You can of course define an array to hold data that is of a particular type like an array of Strings to hold customer names or an array of Doubles to hold customer sales, but what do you do if you want to coordinate that data? This article describes…
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…
Suggested Courses

656 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