C# 實現程序開機自啟動


最近在做一個自動備份文件的小工具,需要用到開機自啟動

下面是代碼

        private void checkBox8_CheckedChanged(object sender, EventArgs e)
        {
           try
            {
                //設置開機自啟動  
                if (checkBox8.Checked == true)
                {
                /*方法一*/
                string StartupPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonStartup);
                //獲得文件的當前路徑
                string dir = Directory.GetCurrentDirectory();
                //獲取可執行文件的全部路徑
                string exeDir = dir + @"\自動備份.exe.lnk";
                File.Copy(exeDir, StartupPath + @"\自動備份.exe.lnk", true);
                /*方法二*/
                string path = Application.ExecutablePath;
                RegistryKey rk = Registry.LocalMachine;
                RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                rk2.SetValue("JcShutdown", path);
                rk2.Close();
                rk.Close();

                }
                //取消開機自啟動  
                else
                {
                    /*方法一*/
                    string StartupPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonStartup);
                    System.IO.File.Delete(StartupPath + @"\EcgNetPlug.exe.lnk");
                    /*方法二*/
                    string path = Application.ExecutablePath;
                    RegistryKey rk = Registry.LocalMachine;
                    RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                    rk2.DeleteValue("JcShutdown", false);
                    rk2.Close();
                    rk.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

第一種方法原理是直接把可執行文件的快捷方式復制到系統的啟動目錄里,這種方式不會被安全軟件攔截,不需要額外的權限

第二種方式是直接寫注冊表,這種方式可能會把安全軟件攔截

大家可以自己試試,有問題可以留言,我也是邊學邊做

 

作者:逐夢
出處:http://www.cnblogs.com/huanjun/
本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM