C#/WPF/WinForm/.NET程序代碼實現軟件程序開機自動啓動的兩種常用方法函數的示例與實例帶詳細註釋
方法一:將軟件的快捷方式創建到計算機的自動啓動目錄下(不需要管理員權限)
1.必要引用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using IWshRuntimeLibrary;
using System.Diagnostics;
2.代碼實現-只需要調用SetMeAutoStart(bool onOff)方法就可以了,參數onOff表示自啓開關
/// <summary>
/// 快捷方式名稱-任意自定義
/// </summary>
private const string QuickName = "TCNVMClient";
/// <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>
/// 設置開機自動啓動-只需要調用改方法就可以了參數裏面的bool變量是控制開機啓動的開關的,默認爲開啓自啓啓動
/// </summary>
/// <param name="onOff">自啓開關</param>
public void SetMeAutoStart(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, "中吉售貨機");
}
}
else//開機不啓動
{
//獲取啓動路徑應用程序快捷方式的路徑集合
List<string> shortcutPaths = GetQuickFromFolder(systemStartPath, appAllPath);
//存在快捷方式則遍歷全部刪除
if (shortcutPaths.Count > 0)
{
for (int i = 0; i < shortcutPaths.Count; i++)
{
DeleteFile(shortcutPaths[i]);
}
}
}
//創建桌面快捷方式-如果需要可以取消註釋
//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)
{
string temp = ex.Message;
temp = "";
}
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++)
{
//files[i] = string.Format("{0}\\{1}", directory, files[i]);
tempStr = 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 "";
}
}
/// <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>
public void CreateDesktopQuick(string desktopPath = "", string quickName = "", string appPath = "")
{
List<string> shortcutPaths = GetQuickFromFolder(desktopPath, appPath);
//如果沒有則創建
if (shortcutPaths.Count < 1)
{
CreateShortcut(desktopPath, quickName, appPath, "軟件描述");
}
}
方法二:修改計算機註冊表的方式(需要管理員權限)
1.必要引用
using Microsoft.Win32;
using System;
using System.Windows.Forms;
using System.Diagnostics;
2.代碼實現-只需要調用SetMeStart(bool onOff)方法就可以了,參數onOff表示自啓開關
/// <summary>
/// 將本程序設爲開啓自啓
/// </summary>
/// <param name="onOff">自啓開關</param>
/// <returns></returns>
public static bool SetMeStart(bool onOff)
{
bool isOk = false;
string appName = Process.GetCurrentProcess().MainModule.ModuleName;
string appPath = Process.GetCurrentProcess().MainModule.FileName;
isOk = SetAutoStart(onOff, appName, appPath);
return isOk;
}
/// <summary>
/// 將應用程序設爲或不設爲開機啓動
/// </summary>
/// <param name="onOff">自啓開關</param>
/// <param name="appName">應用程序名</param>
/// <param name="appPath">應用程序完全路徑</param>
public static bool SetAutoStart(bool onOff, string appName, string appPath)
{
bool isOk = true;
//如果從沒有設爲開機啓動設置到要設爲開機啓動
if (!IsExistKey(appName) && onOff)
{
isOk = SelfRunning(onOff, appName, @appPath);
}
//如果從設爲開機啓動設置到不要設爲開機啓動
else if (IsExistKey(appName) && !onOff)
{
isOk = SelfRunning(onOff, appName, @appPath);
}
return isOk;
}
/// <summary>
/// 判斷註冊鍵值對是否存在,即是否處於開機啓動狀態
/// </summary>
/// <param name="keyName">鍵值名</param>
/// <returns></returns>
private static bool IsExistKey(string keyName)
{
try
{
bool _exist = false;
RegistryKey local = Registry.LocalMachine;
RegistryKey runs = local.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
if (runs == null)
{
RegistryKey key2 = local.CreateSubKey("SOFTWARE");
RegistryKey key3 = key2.CreateSubKey("Microsoft");
RegistryKey key4 = key3.CreateSubKey("Windows");
RegistryKey key5 = key4.CreateSubKey("CurrentVersion");
RegistryKey key6 = key5.CreateSubKey("Run");
runs = key6;
}
string[] runsName = runs.GetValueNames();
foreach (string strName in runsName)
{
if (strName.ToUpper() == keyName.ToUpper())
{
_exist = true;
return _exist;
}
}
return _exist;
}
catch
{
return false;
}
}
/// <summary>
/// 寫入或刪除註冊表鍵值對,即設爲開機啓動或開機不啓動
/// </summary>
/// <param name="isStart">是否開機啓動</param>
/// <param name="exeName">應用程序名</param>
/// <param name="path">應用程序路徑帶程序名</param>
/// <returns></returns>
private static bool SelfRunning(bool isStart, string exeName, string path)
{
try
{
RegistryKey local = Registry.LocalMachine;
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)
{
string ss = ex.Message;
return false;
//throw;
}
return true;
}
3.如何獲取管理員權限請參考
C#如何以管理員身份運行程序 - 酷小孩 - 博客園 https://www.cnblogs.com/babycool/p/3569183.html
C#程序以管理員權限運行 - Cosmic_Spy - 博客園 https://www.cnblogs.com/Interkey/p/RunAsAdmin.html
4.實測穩定可用,希望對你有幫助,謝謝支持。