使用C#的WPF、WinForm框架開發的Windows應用程序,經常會有需要實現開啓自啓動功能的需求,本文將介紹兩種編程實現方式,包含示例代碼。
方法1 修改註冊表
將程序路徑寫入計算機開機啓動的註冊表中,這種方式需要進行寫入註冊表操作的程序具有計算機管理員權限。至於如何實現讓程序具有管理員權限,可參考之前的博客WPF實戰小技巧(七):實現以管理員身份運行
添加引用:
using Microsoft.Win32;
方法1示例代碼:
/// <summary>
/// 判斷註冊鍵值對是否存在,即是否處於開機啓動狀態
/// </summary>
/// <param name="keyName">鍵值名</param>
/// <returns></returns>
private bool isKeyExist(string keyName)
{
bool isExist = false;
try
{
using (RegistryKey local = Registry.LocalMachine)
{
using (RegistryKey runs = local.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true))
{
if (runs != null)
{
string[] runsNames = runs.GetValueNames();
foreach (string strName in runsNames)
{
if (strName.ToUpper() == keyName.ToUpper())
{
isExist = true;
break;
}
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return isExist;
}
/// <summary>
/// 寫入或刪除註冊表鍵值對,即設爲開機啓動或開機不啓動
/// </summary>
/// <param name="isStart">是否開機啓動</param>
/// <param name="exeName">應用程序名</param>
/// <param name="path">應用程序路徑帶程序名</param>
/// <returns></returns>
private bool setAutoRunning(bool isStart, string exeName, string path)
{
try
{
using (RegistryKey local = Registry.LocalMachine)
{
using (RegistryKey key = local.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true))
{
if (key == null)
{
local.CreateSubKey("SOFTWARE//Microsoft//Windows//CurrentVersion//Run");
}
//若開機自啓動,則添加鍵值對,否則刪除鍵值對
if (isStart)
{
key.SetValue(exeName, path);
key.Close();
}
else
{
string[] keyNames = key.GetValueNames();
foreach (string keyName in keyNames)
{
if (keyName.ToUpper() == exeName.ToUpper())
{
key.DeleteValue(exeName);
key.Close();
}
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return false;
}
return true;
}
方法2 自啓動目錄下添加快捷方式
如果不想使用管理員權限,也可將應用程序的快捷方式創建到計算機的自啓動目錄下,實現開機自啓動。
添加引用:
using System.IO;
using System.Diagnostics;
using IWshRuntimeLibrary; //添加引用,在 Com 中搜索 Windows Script Host Object Model
方法2示例代碼:
/// <summary>
/// 自定義快捷方式名稱
/// </summary>
private const string quickName = "AppClient";
/// <summary>
/// 自動獲取系統自動啓動目錄
/// </summary>
private string systemStartPath
{
get
{
return Environment.GetFolderPath(Environment.SpecialFolder.Startup);
}
}
/// <summary>
/// 自動獲取程序完整路徑
/// </summary>
private string appAllPath
{
get
{
return Process.GetCurrentProcess().MainModule.FileName;
}
}
/// <summary>
/// 自動獲取桌面目錄
/// </summary>
private string desktopPath
{
get
{
return Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
}
}
/// <summary>
/// 設置開機自啓動
/// </summary>
/// <param name="onOff">自啓開關</param>
public void SetAutoStart(bool onOff = true)
{
if (onOff) //開機啓動
{
//獲取啓動路徑應用程序快捷方式的路徑集合
List<string> shortcutPaths = GetQuickFromFolder(systemStartPath, appAllPath);
//存在2個以快捷方式則保留一個快捷方式,避免重複
if (shortcutPaths.Count >= 2)
{
for (int i = 1; i < shortcutPaths.Count; i++)
{
DeleteFile(shortcutPaths[i]);
}
}
else if (shortcutPaths.Count < 1)//不存在則創建快捷方式
{
CreateShortcut(systemStartPath, quickName, appAllPath, "Client");
}
}
else //開機不啓動
{
//獲取啓動路徑應用程序快捷方式的路徑集合
List<string> shortcutPaths = GetQuickFromFolder(systemStartPath, appAllPath);
//存在快捷方式則遍歷全部刪除
if (shortcutPaths.Count > 0)
{
for (int i = 0; i < shortcutPaths.Count; i++)
{
DeleteFile(shortcutPaths[i]);
}
}
}
//創建桌面快捷方式
this.CreateDesktopQuick(desktopPath, quickName, appAllPath);
}
/// <summary>
/// 向目標路徑創建指定文件的快捷方式
/// </summary>
/// <param name="directory">目標目錄</param>
/// <param name="shortcutName">快捷方式名字</param>
/// <param name="targetPath">文件完全路徑</param>
/// <param name="description">描述</param>
/// <param name="iconLocation">圖標地址</param>
/// <returns></returns>
private bool CreateShortcut(string directory, string shortcutName, string targetPath, string description = null, string iconLocation = null)
{
try
{
//目錄不存在則創建
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
//添加引用 Com 中搜索 Windows Script Host Object Model
string shortcutPath = Path.Combine(directory, string.Format("{0}.lnk", shortcutName)); //合成路徑
WshShell shell = new IWshRuntimeLibrary.WshShell();
IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutPath); //創建快捷方式對象
shortcut.TargetPath = targetPath; //指定目標路徑
shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath); //設置起始位置
shortcut.WindowStyle = 1; //設置運行方式,默認爲常規窗口
shortcut.Description = description; //設置備註
shortcut.IconLocation = string.IsNullOrWhiteSpace(iconLocation) ? targetPath : iconLocation; //設置圖標路徑
shortcut.Save(); //保存快捷方式
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return false;
}
/// <summary>
/// 獲取指定文件夾下指定應用程序的快捷方式路徑集合
/// </summary>
/// <param name="directory">文件夾</param>
/// <param name="targetPath">目標應用程序路徑</param>
/// <returns>目標應用程序的快捷方式</returns>
private List<string> GetQuickFromFolder(string directory, string targetPath)
{
List<string> tempStrs = new List<string>();
tempStrs.Clear();
string tempStr = null;
string[] files = Directory.GetFiles(directory, "*.lnk");
if (files == null || files.Length < 1)
{
return tempStrs;
}
for (int i = 0; i < files.Length; i++)
{
tempStr = this.GetAppPathFromQuick(files[i]);
if (tempStr == targetPath)
{
tempStrs.Add(files[i]);
}
}
return tempStrs;
}
/// <summary>
/// 獲取快捷方式的目標文件路徑-用於判斷是否已經開啓了自動啓動
/// </summary>
/// <param name="shortcutPath"></param>
/// <returns></returns>
private string GetAppPathFromQuick(string shortcutPath)
{
//快捷方式文件的路徑 = @"d:\Test.lnk";
if (System.IO.File.Exists(shortcutPath))
{
WshShell shell = new WshShell();
IWshShortcut shortct = (IWshShortcut)shell.CreateShortcut(shortcutPath);
//快捷方式文件指向的路徑.Text = 當前快捷方式文件IWshShortcut類.TargetPath;
//快捷方式文件指向的目標目錄.Text = 當前快捷方式文件IWshShortcut類.WorkingDirectory;
return shortct.TargetPath;
}
else
{
return string.Empty;
}
}
/// <summary>
/// 根據路徑刪除文件-用於取消自啓時從計算機自啓目錄刪除程序的快捷方式
/// </summary>
/// <param name="path">路徑</param>
private void DeleteFile(string path)
{
FileAttributes attr = System.IO.File.GetAttributes(path);
if (attr == FileAttributes.Directory)
{
Directory.Delete(path, true);
}
else
{
System.IO.File.Delete(path);
}
}
/// <summary>
/// 在桌面上創建快捷方式-如果需要可以調用
/// </summary>
/// <param name="desktopPath">桌面地址</param>
/// <param name="appPath">應用路徑</param>
private void CreateDesktopQuick(string desktopPath = "", string quickName = "", string appPath = "")
{
List<string> shortcutPaths = this.GetQuickFromFolder(desktopPath, appPath);
//如果沒有則創建
if (shortcutPaths.Count < 1)
{
this.CreateShortcut(desktopPath, quickName, appPath, "軟件描述");
}
}