Author : Louis
Date Submitted : 7/5/2005
Category : Windows Operations
Compatibility : VB 6
This code has been accessed 11320 times.
Task : Code to get a program to run at startup
Declarations
Code
Private Sub SetRunAtStartup(ByVal app_name As String, ByVal app_path As String, Optional ByVal run_at_startup As Boolean = True)
Dim hKey As Long
Dim key_value As String
Dim status As Long
On Error GoTo SetStartupError
' Open the key, creating it if it doesn't exist.
If RegCreateKeyEx(HKEY_CURRENT_USER, _
"Software\Microsoft\Windows\CurrentVersion\Run", _
ByVal 0&, ByVal 0&, ByVal 0&, _
KEY_WRITE, ByVal 0&, hKey, _
ByVal 0&) <> ERROR_SUCCESS _
Then
MsgBox "Error " & Err.Number & " opening key" & _
vbCrLf & Err.Description
Exit Sub
End If
' See if we should run at startup.
If run_at_startup Then
' Create the key.
key_value = app_path & "\" & app_name & ".exe" & vbNullChar
status = RegSetValueEx(hKey, App.EXEName, 0, REG_SZ, _
ByVal key_value, Len(key_value))
If status <> ERROR_SUCCESS Then
MsgBox "Error " & Err.Number & " setting key" & _
vbCrLf & Err.Description
End If
Else
' Delete the value.
RegDeleteValue hKey, app_name
End If
' Close the key.
RegCloseKey hKey
Exit Sub
SetStartupError:
MsgBox Err.Number & " " & Err.Description
Exit Sub
End Sub
' Return True if the program is set to run at startup.
Private Function WillRunAtStartup(ByVal app_name As String) As Boolean
Dim hKey As Long
Dim value_type As Long
' See if the key exists.
If RegOpenKeyEx(HKEY_CURRENT_USER, _
"Software\Microsoft\Windows\CurrentVersion\Run", _
0, KEY_READ, hKey) = ERROR_SUCCESS _
Then
' Look for the subkey named after the application.
WillRunAtStartup = _
(RegQueryValueEx(hKey, app_name, _
ByVal 0&, value_type, ByVal 0&, ByVal 0&) = _
ERROR_SUCCESS)
' Close the registry key handle.
RegCloseKey hKey
Else
' Can't find the key.
WillRunAtStartup = False
End If
End Function
' Clear or set the key that makes the program run at startup.
Private Sub chkRun_Click()
' If m_IgnoreEvents Then Exit Sub
' SetRunAtStartup App.EXEName, App.Path, _
' (chkRun.Value = vbChecked)
End Sub
Private Sub Form_Click()
End
End Sub
Private Sub Form_Load()
If m_IgnoreEvents Then Exit Sub
SetRunAtStartup App.EXEName, App.Path
m_IgnoreEvents = True
WillRunAtStartup (App.EXEName)
m_IgnoreEvents = False
End Sub