winform(c#) 開機自動啓動程序

public void SetAutoRun(string fileName, bool isAutoRun)  
{  
    RegistryKey reg = null;  
    try 
    {  
        if (!System.IO.File.Exists(fileName))  
            throw new Exception("該文件不存在!");  
        String name = fileName.Substring(fileName.LastIndexOf(@"/") + 1);  
        reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE/Microsoft/Windows/CurrentVersion/Run", true);  
        if (reg == null)  
            reg = Registry.LocalMachine.CreateSubKey(@"SOFTWARE/Microsoft/Windows/CurrentVersion/Run");  
        if (isAutoRun)  
            reg.SetValue(name, fileName);  
        else 
            reg.SetValue(name, false);  
        lbl_autorunerr.Visible = false;  
    }  
    catch 
    {  
        lbl_autorunerr.Visible = true;  
        //throw new Exception(ex.ToString());  
    }  
    finally 
    {  
        if (reg != null)  
            reg.Close();  
    }  

        public void SetAutoRun(string fileName, bool isAutoRun)
        {
            RegistryKey reg = null;
            try
            {
                if (!System.IO.File.Exists(fileName))
                    throw new Exception("該文件不存在!");
                String name = fileName.Substring(fileName.LastIndexOf(@"/") + 1);
                reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE/Microsoft/Windows/CurrentVersion/Run", true);
                if (reg == null)
                    reg = Registry.LocalMachine.CreateSubKey(@"SOFTWARE/Microsoft/Windows/CurrentVersion/Run");
                if (isAutoRun)
                    reg.SetValue(name, fileName);
                else
                    reg.SetValue(name, false);
                lbl_autorunerr.Visible = false;
            }
            catch
            {
                lbl_autorunerr.Visible = true;
                //throw new Exception(ex.ToString());
            }
            finally
            {
                if (reg != null)
                    reg.Close();
            }
        }

使用的時候,直接調用SetAutoRun函數即可,這裏解釋一下兩個參數的含義:

fileName:需要設置自動啓動程序的路徑,若爲當前程序可直接傳遞Application.ExecutablePath。

isAutoRun:是否自動運行,爲false時,取消自動運行。

例:  SetAutoRun(Application.ExecutablePath, true);  //設置自動啓動當前程序

        SetAutoRun(Application.ExecutablePath, false);  //取消自動啓動

 

本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/cbq926/archive/2009/02/23/3930257.aspx

發佈了21 篇原創文章 · 獲贊 17 · 訪問量 60萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章