Reputation: 4541
I have been trying to make my app run on startup. I have added a context menu which should switch this feature on and off. The context menu has the "check" feature enabled (gets a check mark when checked) on its left.
//
// menu_startup
//
this.menu_startup.Name = "menu_startup";
this.menu_startup.ShortcutKeyDisplayString = "";
this.menu_startup.Size = new System.Drawing.Size(201, 22);
this.menu_startup.Text = "Run on startup";
this.menu_startup.Click += new System.EventHandler(this.menu_startup_Click);
And this is what I did in Form1.cs
public string regKey = "IMGit";
public Form1()
{
InitializeComponent();
notifyIcon1.ContextMenuStrip = contextMenuStrip1;
RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (rkApp.GetValue(this.regKey) == null)
{
this.menu_startup.Checked = false;
}
else
{
this.menu_startup.Checked = true;
}
this.menu_about.Click += menu_about_Click; // Ignore
this.menu_exit.Click += menu_exit_Click; // Ignore
this.menu_startup.Click += menu_startup_Click;
}
private void menu_startup_Click(object sender, EventArgs e)
{
RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (rkApp.GetValue(this.regKey) == null)
{
rkApp.SetValue(this.regKey, Application.ExecutablePath.ToString());
}
else
{
rkApp.DeleteValue(this.regKey, false);
}
}
I can't see what I am doing wrong here. This should set a new registry entry for my app.
If I add the lines of code to create the registry entry in the constructor, it will create the entry just fine.
Ideas?
Upvotes: 1
Views: 2236
Reputation: 4541
Making a lambda function in the constructor solved the issue.
this.menu_startup.Click += (s, ea) =>
{
RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
string appPath = Application.ExecutablePath.ToString();
this.menu_startup.Checked = (rkApp.GetValue(this.regKey) == null);
if (rkApp.GetValue(this.regKey) == null)
{
rkApp.SetValue(this.regKey, appPath);
}
else
{
rkApp.DeleteValue(this.regKey, false);
}
};
Upvotes: 0
Reputation: 65534
If you want the registry key created on application startup, you need to call the menu_startup_Click
method from the constructor.
public Form1()
{
InitializeComponent();
notifyIcon1.ContextMenuStrip = contextMenuStrip1;
//Make the call to add the registry key here (plus Check or Uncheck the menu)
menu_startup_Click(null,null);
this.menu_startup.Click += menu_startup_Click;
}
private void menu_startup_Click(object sender, EventArgs e)
{
RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
//Check or Uncheck the menu
this.menu_startup.Checked = (rkApp.GetValue(this.regKey) == null)
if (rkApp.GetValue(this.regKey) == null)
{
rkApp.SetValue(this.regKey, Application.ExecutablePath.ToString());
}
else
{
rkApp.DeleteValue(this.regKey, false);
}
}
Upvotes: 1