Tuesday, July 15, 2008

C#: Set And Unset Auto-start For Windows Application

I found this useful C# class in this MSDN forum that provides an easy way to enable and disable an application auto-run in Windows.

With a little modification, I made it to be easily called by any project. What you need to do is just pass in the 'Key Name' and 'Assembly Location' parameters.

Here is the complete class:
using Microsoft.Win32;

/// <summary>
/// Utility.
/// </summary>
public class Util
{
private const string RUN_LOCATION = @"Software\Microsoft\Windows\CurrentVersion\Run";

/// <summary>
/// Sets the autostart value for the assembly.
/// </summary>
/// <param name="keyName">Registry Key Name</param>
/// <param name="assemblyLocation">Assembly location (e.g. Assembly.GetExecutingAssembly().Location)</param>
public static void SetAutoStart(string keyName, string assemblyLocation)
{
RegistryKey key = Registry.CurrentUser.CreateSubKey(RUN_LOCATION);
key.SetValue(keyName, assemblyLocation);
}

/// <summary>
/// Returns whether auto start is enabled.
/// </summary>
/// <param name="keyName">Registry Key Name</param>
/// <param name="assemblyLocation">Assembly location (e.g. Assembly.GetExecutingAssembly().Location)</param>
public static bool IsAutoStartEnabled(string keyName, string assemblyLocation)
{
RegistryKey key = Registry.CurrentUser.OpenSubKey(RUN_LOCATION);
if (key == null)
return false;

string value = (string)key.GetValue(keyName);
if (value == null)
return false;

return (value == assemblyLocation);
}

/// <summary>
/// Unsets the autostart value for the assembly.
/// </summary>
/// <param name="keyName">Registry Key Name</param>
public static void UnSetAutoStart(string keyName)
{
RegistryKey key = Registry.CurrentUser.CreateSubKey(RUN_LOCATION);
key.DeleteValue(keyName);
}
}
Sample Usage:
string keyName = "MyProgramName";
string assemblyLocation = Assembly.GetExecutingAssembly().Location; // Or the EXE path.

// Set Auto-start.
Util.SetAutoStart(keyName, assemblyLocation);

// Unset Auto-start.
if (Util.IsAutoStartEnabled(keyName, assemblyLocation))
Util.UnSetAutoStart(keyName);

If you find this post helpful, would you buy me a coffee?


10 comments:

  1. How can we call *sample usage* code from installation package? I mean first the .msi package must change the registry key so .exe file can start automatically?

    ReplyDelete
  2. hi,
    it seems that IsAutoStartEnabled method is not complete. Why don't you correct all the misses and post normal version?

    ReplyDelete
  3. RegistryKey ... use Dispose and close for the key variable

    ReplyDelete
  4. Can this be used on two buttons?

    ReplyDelete
  5. if the programm was started manually - function IsAutoStartEnabled() works correctly, but if program was "autostarted" it gives me always FALSE, how can i fix this or what can be a reason

    programm seems to be started with the same user

    ReplyDelete