72

I made an application that launches during startup, with the next code below.
The process runs on the process manager tool after the restart, but I can't see the application on the screen. When I open the same .exe file from the startup registry value the program runs perfect.

// The path to the key where Windows looks for startup applications
RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

// Add the value in the registry so that the application runs at startup
rkApp.SetValue("MyApp", Application.ExecutablePath.ToString());

What can I do to fix it up?

radarbob
  • 4,964
  • 2
  • 23
  • 36
Oded .S
  • 1,081
  • 2
  • 11
  • 18
  • is your application targeting x86, and your computer running on a 64 bit os ? – Steve B Feb 23 '11 at 10:29
  • 1
    What do you see in the registry? Does `rkApp.SetValue` succeed? – Aliostad Feb 23 '11 at 10:34
  • @Aliostad, I think we can assume it works because the post says the registry value contains a valid path. – Phil Gan Feb 23 '11 at 10:45
  • @bloodix, can you get a screenshot from Reg Edit to show what's in your Run registry key? Does the registry entry for your exe look similar to the other entries there? – AAT Feb 23 '11 at 11:01
  • Steve B - my application targeting is X86 and my computer running on a 32 bit os, but with a 64 bit cappability. – Oded .S Feb 23 '11 at 12:58
  • @Aliostad, I checked another .exe process on the same registery directory manualy, and it worked. What can be the cause to my specific application to have a problem running – Oded .S Feb 23 '11 at 13:03

12 Answers12

69

Code is here (Win form app):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;

namespace RunAtStartup
{
    public partial class frmStartup : Form
    {
        // The path to the key where Windows looks for startup applications
        RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

        public frmStartup()
        {
            InitializeComponent();
            // Check to see the current state (running at startup or not)
            if (rkApp.GetValue("MyApp") == null)
            {
                // The value doesn't exist, the application is not set to run at startup
                chkRun.Checked = false;
            }
            else
            {
                // The value exists, the application is set to run at startup
                chkRun.Checked = true;
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (chkRun.Checked)
            {
                // Add the value in the registry so that the application runs at startup
                rkApp.SetValue("MyApp", Application.ExecutablePath);
            }
            else
            {
                // Remove the value from the registry so that the application doesn't start
                rkApp.DeleteValue("MyApp", false);
            }
        }
    }
}
Ondrej Slinták
  • 31,386
  • 20
  • 94
  • 126
Adrew
  • 707
  • 4
  • 2
  • 9
    @BoltClock does it really matter? Also, the questions isn't a WPF question, or even have anything to do with WPF in the first place besides the fact that it was mentioned. Even then though, that was just extraneous information. To be completely honest the WPF tag should be removed that the question details pertaining to it should also get purged. – Kelly Elton Nov 03 '14 at 20:53
  • @kelton52: Agreed on your last point. As well any and all information in the answer pertaining to WinForms should be cleaned up - just look at *all* that boilerplate. – BoltClock Nov 23 '14 at 06:32
  • 3
    @Dinav Ahire: `chkRun` is the (checkable)form control which displays and controls the start-with-windows state of the application. – Glitch Sep 01 '15 at 04:25
  • Actually, WPF is relevant because Application.ExecutablePath will not work in a WPF app. There are other answers with (currently) lower votes with better answers. – stricq Sep 03 '16 at 00:36
  • The path **`SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run`** is important. – Muhammad Khuzaima Umair Aug 11 '22 at 03:38
46

Try this code:

private void RegisterInStartup(bool isChecked)
{
    RegistryKey registryKey = Registry.CurrentUser.OpenSubKey
            ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
    if (isChecked)
    {
        registryKey.SetValue("ApplicationName", Application.ExecutablePath);
    }
    else
    {
        registryKey.DeleteValue("ApplicationName");
    }
}

Source (dead): http://www.dotnetthoughts.net/2010/09/26/run-the-application-at-windows-startup/

Archived link: https://web.archive.org/web/20110104113608/http://www.dotnetthoughts.net/2010/09/26/run-the-application-at-windows-startup/

Issung
  • 385
  • 3
  • 14
Anuraj
  • 18,859
  • 7
  • 53
  • 79
  • 17
    Since question is WPF related, notice that `Application.ExecutablePath` is part of `System.Windows.Forms`, and will result in `cannot resolve symbol` in WPF project. You can use `System.Reflection.Assembly.GetExecutingAssembly().Location` as proper replacement. – itsho Feb 22 '15 at 07:02
  • 5
    Assembly.GetExecutingAssembly() will get the assembly currently running the code. It will not get the correct assembly if the code is executed on another assembly. Use Assembly.GetEntryAssembly() instead. – SilverCorvus Oct 18 '15 at 06:48
  • The link is dead. – Hakan Fıstık Aug 14 '17 at 10:17
18

You could try copying a shortcut to your application into the startup folder instead of adding things to the registry. You can get the path with Environment.SpecialFolder.Startup. This is available in all .net frameworks since 1.1.

Alternatively, maybe this site will be helpful to you, it lists a lot of the different ways you can get an application to auto-start.

Phil Gan
  • 2,813
  • 2
  • 29
  • 38
13
public class StartUpManager
{
    public static void AddApplicationToCurrentUserStartup()
    {
        using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
        {
            key.SetValue("My ApplicationStartUpDemo", "\"" + System.Reflection.Assembly.GetExecutingAssembly().Location + "\"");
        }
    }

    public static void AddApplicationToAllUserStartup()
    {
        using (RegistryKey key =     Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
        {
            key.SetValue("My ApplicationStartUpDemo", "\"" + System.Reflection.Assembly.GetExecutingAssembly().Location + "\"");
        }
    }

    public static void RemoveApplicationFromCurrentUserStartup()
    {
         using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
         {
             key.DeleteValue("My ApplicationStartUpDemo", false);
         }
    }

    public static void RemoveApplicationFromAllUserStartup()
    {
        using (RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
        {
            key.DeleteValue("My ApplicationStartUpDemo", false);
        }
    }

    public static bool IsUserAdministrator()
    {
        //bool value to hold our return value
        bool isAdmin;
        try
        {
            //get the currently logged in user
            WindowsIdentity user = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(user);
            isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
        }
        catch (UnauthorizedAccessException ex)
        {
            isAdmin = false;
        }
        catch (Exception ex)
        {
            isAdmin = false;
        }
        return isAdmin;
    }
}

you can check whole article here

Rashid Malik
  • 131
  • 1
  • 4
  • Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/a/8259/159034) to include the essential parts of the answer here, and provide the link for reference. – Kevin Brown-Silva Mar 03 '15 at 01:23
  • 1
    +1 for including the section for using "Registry.LocalMachine.OpenSubKey" adding/removing the key for all the users. – Ashish Gupta Sep 04 '16 at 16:15
5

its very simple

add two part in code :

1- add namespace:

using Microsoft.Win32;

2-add application to registery :

RegistryKey key=Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
key.SetValue("your_app_name", Application.ExecutablePath);

if you want delete app from registery:

key.DeleteValue("your_app_name",false);
mamal
  • 1,791
  • 20
  • 14
1

I did not find any of the above code worked. Maybe that's because my app is running .NET 3.5. I don't know. The following code worked perfectly for me. I got this from a senior level .NET app developer on my team.

Write(Microsoft.Win32.Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run\", "WordWatcher", "\"" + Application.ExecutablePath.ToString() + "\"");
public bool Write(RegistryKey baseKey, string keyPath, string KeyName, object Value)
{
    try
    {
        // Setting 
        RegistryKey rk = baseKey;
        // I have to use CreateSubKey 
        // (create or open it if already exits), 
        // 'cause OpenSubKey open a subKey as read-only 
        RegistryKey sk1 = rk.CreateSubKey(keyPath);
        // Save the value 
        sk1.SetValue(KeyName.ToUpper(), Value);

        return true;
    }
    catch (Exception e)
    {
        // an error! 
        MessageBox.Show(e.Message, "Writing registry " + KeyName.ToUpper());
        return false;
    }
}
slavoo
  • 5,798
  • 64
  • 37
  • 39
1

first I tried the code below and it was not working

RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
rkApp.SetValue("MyAPP", Application.ExecutablePath.ToString());

Then, I changed CurrentUser with LocalMachine and it works

RegistryKey rkApp = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
rkApp.SetValue("MyAPP", Application.ExecutablePath.ToString());
srcnaks
  • 243
  • 3
  • 13
0

An open source application called "Startup Creator" configures Windows Startup by creating a script while giving an easy to use interface. Utilizing powerful VBScript, it allows applications or services to start up at timed delay intervals, always in the same order. These scripts are automatically placed in your startup folder, and can be opened back up to allow modifications in the future.

http://startupcreator.codeplex.com/

Jake Soenneker
  • 179
  • 1
  • 12
0

for WPF: (where lblInfo is a label, chkRun is a checkBox)

this.Topmost is just to keep my app on the top of other windows, you will also need to add a using statement " using Microsoft.Win32; ", StartupWithWindows is my application's name

public partial class MainWindow : Window
    {
        // The path to the key where Windows looks for startup applications
        RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

        public MainWindow()
        {
            InitializeComponent();
            if (this.IsFocused)
            {
                this.Topmost = true;
            }
            else
            {
                this.Topmost = false;
            }

            // Check to see the current state (running at startup or not)
            if (rkApp.GetValue("StartupWithWindows") == null)
            {
                // The value doesn't exist, the application is not set to run at startup, Check box
                chkRun.IsChecked = false;
                lblInfo.Content = "The application doesn't run at startup";
            }
            else
            {
                // The value exists, the application is set to run at startup
                chkRun.IsChecked = true;
                lblInfo.Content = "The application runs at startup";
            }
            //Run at startup
            //rkApp.SetValue("StartupWithWindows",System.Reflection.Assembly.GetExecutingAssembly().Location);

            // Remove the value from the registry so that the application doesn't start
            //rkApp.DeleteValue("StartupWithWindows", false);

        }

        private void btnConfirm_Click(object sender, RoutedEventArgs e)
        {
            if ((bool)chkRun.IsChecked)
            {
                // Add the value in the registry so that the application runs at startup
                rkApp.SetValue("StartupWithWindows", System.Reflection.Assembly.GetExecutingAssembly().Location);
                lblInfo.Content = "The application will run at startup";
            }
            else
            {
                // Remove the value from the registry so that the application doesn't start
                rkApp.DeleteValue("StartupWithWindows", false);
                lblInfo.Content = "The application will not run at startup";
            }
        }

    }
shakram02
  • 10,812
  • 4
  • 22
  • 21
0

If you could not set your application autostart you can try to paste this code to manifest

<requestedExecutionLevel  level="asInvoker" uiAccess="false" />

or delete manifest I had found it in my application

Abhishek Pandey
  • 13,302
  • 8
  • 38
  • 68
-1

I think there is a specific Win32 API call which takes the application path and puts it in the registry automatically for you in the proper location, I've used it in the past but I don't remember the function name anymore.

Rob
  • 45,296
  • 24
  • 122
  • 150
Davide Piras
  • 43,984
  • 10
  • 98
  • 147
-1

OK here are my 2 cents: try passing path with each backslash as double backslash. I have found sometimes calling WIN API requires that.

Aliostad
  • 80,612
  • 21
  • 160
  • 208
  • 4
    -1 because it isn't WIN API that requires that, it is how languages like C# and C++ interpret the backslash character in a string. – AAT Mar 05 '11 at 12:02
  • You will be surprised my friend that sometimes they also need it. I will post when I find the example - it was a while back. – Aliostad Mar 05 '11 at 13:12