L'esempio sotto mostra come eseguire il Notepad all'avvio di Windows.
NOTA:
nell'esempio ho usato la chiave CurrentUser , che vale per il solo utente corrente.
per tutti gli utenti si deve usare la chiave LocalMachine
1 - apri un nuovo progetto
2 - sul Form1 aggiungi un controllo CheckBox con il nome: chkRunAtStartupOrRemove
3 - copia il codice sotto:
codice:
Imports Microsoft.Win32
Public Class Form1
Dim myApplicationName As String = ""
Dim myApplicationPath As String = ""
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
myApplicationName = "Notepad"
myApplicationPath = "C:\Windows\Notepad.exe"
End Sub
Public Sub RunAtStartup(ByVal ApplicationName As String, ByVal ApplicationPath As String)
Dim CurrentUserRun As Microsoft.Win32.RegistryKey = Registry.CurrentUser.CreateSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run")
With CurrentUserRun
.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True)
.SetValue(ApplicationName, ApplicationPath)
End With
End Sub
Public Sub RemoveFromStartup(ByVal ApplicationName As String)
Dim CurrentUserRun As Microsoft.Win32.RegistryKey = Registry.CurrentUser.CreateSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run")
With CurrentUserRun
.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True)
.DeleteValue(ApplicationName, False)
End With
End Sub
Private Sub chkRunAtStartupOrRemove_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles chkRunAtStartupOrRemove.CheckedChanged
' occorrono sia il nome che il percorso
If String.IsNullOrEmpty(myApplicationName) Or String.IsNullOrEmpty(myApplicationPath) Then
MessageBox.Show("Indicare il Nome ed il percorso dell'applicazione da avviare.", "Dati mancanti", MessageBoxButtons.OK, MessageBoxIcon.Information)
Exit Sub
End If
' verifico l'esistenza
If My.Computer.FileSystem.FileExists(myApplicationPath) = False Then
MessageBox.Show("File non trovato.")
Exit Sub
End If
If chkRunAtStartupOrRemove.Checked = True Then
' aggiungo al registro
RunAtStartup(myApplicationName, myApplicationPath)
Else
' rimuovo dal registro
RemoveFromStartup(myApplicationName)
End If
End Sub
End Class