1. 程式人生 > >C#客戶端(WinForm)開機自動啟動實現

C#客戶端(WinForm)開機自動啟動實現

1.原理:需要開機自啟動的程式,需要將其啟動程式的路徑寫到登錄檔中指定的資料夾下

2. 寫入登錄檔的方式有兩種

a.在生成安裝程式時配置

b.在程式執行時,動態配置。

方法一:在生成安裝程式時配置 右擊安裝編輯程式,在“檢視”選單中,選擇“登錄檔”。通過右鍵選單新建"鍵",創建出如圖所示的路徑。 右鍵Run,新建“字串值”。為右側的key命名(在登錄檔中不能重名),並在屬性中指定它的value值。 注:[TARGETDIR]表示在程式的安裝路徑。 方法二:在程式執行時指定是否開機啟動   在程式執行時,通過呼叫如下方法實現開機啟動
/// <summary>  
        /// 修改程式在登錄檔中的鍵值  
        /// </summary>  
        /// <param name="isAuto">true:開機啟動,false:不開機自啟</param> 
        public static void AutoStart(bool isAuto)
        {
            try
            {
                if (isAuto == true)
                {
                    RegistryKey R_local = Registry.LocalMachine;//RegistryKey R_local = Registry.CurrentUser;
                    RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                    R_run.SetValue("應用名稱", Application.ExecutablePath);
                    R_run.Close();
                    R_local.Close();
                }
                else
                {
                    RegistryKey R_local = Registry.LocalMachine;//RegistryKey R_local = Registry.CurrentUser;
                    RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                    R_run.DeleteValue("應用名稱", false);
                    R_run.Close();
                    R_local.Close();
                }

                //GlobalVariant.Instance.UserConfig.AutoStart = isAuto;
            }
            catch (Exception)
            {
                //MessageBoxDlg dlg = new MessageBoxDlg();
                //dlg.InitialData("您需要管理員許可權修改", "提示", MessageBoxButtons.OK, MessageBoxDlgIcon.Error);
                //dlg.ShowDialog();
                MessageBox.Show("您需要管理員許可權修改", "提示");
            }

注:該程式的啟動項設定到HKEY_Current_User 下,推薦。如果想改在HKEY_LOCAL_MACHINE,只需將CurrentUser改為LocalMachine,即
Rkey = Microsoft.Win32.Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");  
操作登錄檔有可能會需要程式有管理員許可權,這時候就要在程式以管理員身份啟動並執行。此時應進行以下操作。 1、在程式中新增程式清單檔案。通過VS新增,右鍵專案選擇新增選擇新建項,選擇程式清單。如下圖。

2、設定UAC 選項。如圖。

參考文章:http://blog.csdn.net/liyc123youxiang/article/details/45870563