C#設(shè)置程序開機啟動的實現(xiàn)示例
1:獲取當(dāng)前用戶:
System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);2:判斷當(dāng)前用戶是否是管理員如果是則直接啟動否則通過Process啟動:
(如果不這樣處理直接使用非admin權(quán)限對注冊表進行編輯操作程序?qū)螽惓?
if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
{
//如果是管理員則直接啟動
Application.Run(new Form1());
}
else
{
System.Diagnostics.ProcessStartInfo startinfo = new System.Diagnostics.ProcessStartInfo();
//啟動的應(yīng)用程序
startinfo.FileName = Application.ExecutablePath;
//設(shè)置啟動動作,以管理員身份啟動
startinfo.Verb = "runas";
var process= System.Diagnostics.Process.Start(startinfo);
Application.Exit();
}3:對注冊表進行編輯,設(shè)置啟動路徑
RegistryKey runKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run",true);
//當(dāng)前啟動的項目
//string app = Application.ExecutablePath;
//獲取的路徑格式為:D:\Program Files (x86)/360/360Safe/safemon/360tray.exe
//該格式無法達到開機啟動的目的。
string app = System.Reflection.Assembly.GetExecutingAssembly().Location;
//格式:D:\Program Files (x86)\360\360Safe\safemon\360tray.exe
//該格式實現(xiàn)開機啟動
Registry.LocalMachine.CreateSubKey(@"SOFTWARE\MICROSOFT\WINDOWS\CURRENTVERSION\RUN").SetValue("MyAngel", app, RegistryValueKind.String); //打開注冊表中的現(xiàn)有項并設(shè)置其中的鍵值類型4:注銷開機自啟動功能(可選):
//刪除該啟動項
RegistryKey runKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", RegistryKeyPermissionCheck.ReadWriteSubTree);
runKey.DeleteValue("MyAngel");
runKey.Close();5:特別注意事項:
1,雖然使用:
Registry.LocalMachine.CreateSubKey(@"SOFTWARE\MICROSOFT\WINDOWS\CURRENTVERSION\RUN").SetValue("MyAngel", app, RegistryValueKind.String);理論上添加的鍵值信息應(yīng)該是存儲在:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
實際上有可能存儲在:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Run
2,設(shè)置的值其格式必須注意:
SetValue("MyAngel", app, RegistryValueKind.String);app存儲的字符串格式只能是:D:\Program Files (x86)\360\360Safe\safemon\360tray.exe
而不能是:D:\Program Files (x86)/360/360Safe/safemon/360tray.exe
如果格式異常則無法達到開機自啟動的目的。
到此這篇關(guān)于C#設(shè)置程序開機啟動的實現(xiàn)示例的文章就介紹到這了,更多相關(guān)C# 程序開機啟動內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#獲取某路徑文件夾中全部圖片或其它指定格式的文件名的實例方法
在本篇文章里小編給大家整理的是關(guān)于C#獲取某路徑文件夾中全部圖片或其它指定格式的文件名的實例方法,需要的朋友們參考下。2019-10-10
C#中new和override的區(qū)別個人總結(jié)
這篇文章主要介紹了C#中new和override的區(qū)別個人總結(jié),本文以問答的方式講解了new和override的區(qū)別,需要的朋友可以參考下2015-06-06
詳解.NET 6如何實現(xiàn)獲取當(dāng)前登錄用戶信息
這篇文章主要介紹了.NET 6在應(yīng)用開發(fā)時是如何實現(xiàn)當(dāng)前登陸用戶信息獲取的,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起了解一下2022-01-01

