Skip to content

Instantly share code, notes, and snippets.

@iguigova
Created June 25, 2012 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iguigova/2991318 to your computer and use it in GitHub Desktop.
Save iguigova/2991318 to your computer and use it in GitHub Desktop.
AutoStart
public static class CAutoStartUtils
{
public static string exePath
{
get
{
return (ApplicationDeployment.IsNetworkDeployed) ? Path.Combine(CDeploymentInfo.AppPath, exeName) : Assembly.GetExecutingAssembly().Location;
}
}
public static string exeName
{
get { return (ApplicationDeployment.IsNetworkDeployed) ? CDeploymentInfo.AppName : Assembly.GetExecutingAssembly().GetName().Name; }
}
public static bool IsAutoStartEnabled()
{
return IsAutoStartEnabled(Registry.CurrentUser, exeName, exePath);
}
public static void EnableAutoStart()
{
if (!IsAutoStartEnabled(Registry.CurrentUser, exeName, exePath))
ResetAutoStart(Registry.CurrentUser, exeName, exePath);
}
public static void DisableAutoStart()
{
ResetAutoStart(Registry.CurrentUser, exeName, string.Empty);
}
// http://simpcode.blogspot.com/2008/07/c-set-and-unset-auto-start-for-windows.html
private const string RunKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Run";
private static bool IsAutoStartEnabled(RegistryKey key, string name, string path)
{
var autostart = GetAutoStart(key, name);
return !string.IsNullOrEmpty(autostart) && autostart.Contains(path);
}
private static void ResetAutoStart(RegistryKey key, string name, string path)
{
if (string.IsNullOrEmpty(path) && IsAutoStartEnabled(key, name, path))
{
key.CreateSubKey(RunKeyPath).DeleteValue(name);
}
if (!string.IsNullOrEmpty(path) && !IsAutoStartEnabled(key, name, path))
{
key.CreateSubKey(RunKeyPath).SetValue(name, path);
}
}
private static string GetAutoStart(RegistryKey key, string name)
{
// TODO:
// What if the value is not a string and/or is undefined?
var autostart = (string)key.OpenSubKey(RunKeyPath).GetValue(name);
return (!string.IsNullOrEmpty(autostart)) ? autostart : string.Empty;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment