Two Approaches for Auto-Starting Windows Applications
1. Startup Folder Shortcut Method (No Admin Rights Required)
This approach creates a shortcut in the Windows startup folder:
using System;
using System.IO;
using IWshRuntimeLibrary;
public class AutoStartManager
{
private const string AppShortcutName = "MyApplication";
private string StartupPath =>
Environment.GetFolderPath(Environment.SpecialFolder.Startup);
private string AppPath =>
System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
public void ConfigureAutoStart(bool enable)
{
var existingShortcuts = FindAppShortcuts(StartupPath, AppPath);
if (enable)
{
if (existingShortcuts.Count >= 2)
{
for (int i = 1; i < existingShortcuts.Count; i++)
{
File.Delete(existingShortcuts[i]);
}
}
else if (existingShortcuts.Count == 0)
{
CreateStartupShortcut(StartupPath, AppShortcutName, AppPath);
}
}
else
{
foreach (var shortcut in existingShortcuts)
{
File.Delete(shortcut);
}
}
}
private bool CreateStartupShortcut(string folder, string name, string target)
{
try
{
Directory.CreateDirectory(folder);
string shortcutPath = Path.Combine(folder, $"{name}.lnk");
var shell = new WshShell();
IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);
shortcut.TargetPath = target;
shortcut.WorkingDirectory = Path.GetDirectoryName(target);
shortcut.Save();
return true;
}
catch
{
return false;
}
}
}
2. Registry Modification Method (Requires Admin Rights)
This approach modifeis the Windows registry:
using Microsoft.Win32;
public class RegistryAutoStart
{
public static bool SetAutoStart(bool enable)
{
string appName = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
string appPath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
return ConfigureRegistry(enable, appName, appPath);
}
private static bool ConfigureRegistry(bool enable, string name, string path)
{
try
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(
@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true))
{
if (enable)
{
key.SetValue(name, path);
}
else
{
key.DeleteValue(name, false);
}
return true;
}
}
catch
{
return false;
}
}
}
Running Application as Administrator
For registry modification, your app needs admin privileges. Here's how to request them:
using System.Security.Principal;
using System.Diagnostics;
static class Program
{
[STAThread]
static void Main()
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
if (principal.IsInRole(WindowsBuiltInRole.Administrator))
{
Application.Run(new MainForm());
}
else
{
var startInfo = new ProcessStartInfo
{
FileName = Application.ExecutablePath,
UseShellExecute = true,
Verb = "runas"
};
try
{
Process.Start(startInfo);
Application.Exit();
}
catch { }
}
}
}
Alternatively, you can modify the application manifest:
<requestedExecutionLevel
level="requireAdministrator"
uiAccess="false" />