Windows 開機自動執行程式,透過登錄表 HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run(全機器)或 HKCU\...\Run(當前使用者)的字串值實現。
using Microsoft.Win32;
public static class AutoRunHelper {
private const string RunKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
public static void SetAutoRun(string appName, string exePath, bool forAllUsers = false) {
var root = forAllUsers ? Registry.LocalMachine : Registry.CurrentUser;
using (var key = root.CreateSubKey(RunKey)) {
key.SetValue(appName, exePath);
}
}
public static void RemoveAutoRun(string appName, bool forAllUsers = false) {
var root = forAllUsers ? Registry.LocalMachine : Registry.CurrentUser;
using (var key = root.OpenSubKey(RunKey, writable: true)) {
key?.DeleteValue(appName, throwOnMissingValue: false);
}
}
public static bool IsAutoRunEnabled(string appName, bool forAllUsers = false) {
var root = forAllUsers ? Registry.LocalMachine : Registry.CurrentUser;
using (var key = root.OpenSubKey(RunKey)) {
return key?.GetValue(appName) != null;
}
}
}
private void chkAutoRun_CheckedChanged(object sender, EventArgs e) {
string name = Application.ProductName;
string path = Application.ExecutablePath;
if (chkAutoRun.Checked)
AutoRunHelper.SetAutoRun(name, path);
else
AutoRunHelper.RemoveAutoRun(name);
}
HKLM 需管理員權限,建議預設寫 HKCUkey.SetValue(name, "\"" + path + "\"")TaskScheduler COM 介面,支援觸發條件、延遲、最高權限shell:startup 建立捷徑,無需登錄表權限