C# 程序自启动

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;

namespace UPDataClient
{
    /// <summary>
    /// 注册表操作类
    /// </summary>
    class RegisterUtils
    {

        /// <summary>
        /// 判断自启动项是否有该项
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static bool IsRegeditItemExist(string fileName)   
        {   
        string[] subkeyNames;   
        RegistryKey hkml = Registry.LocalMachine;   
        RegistryKey software = hkml.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run",true);   //可写的方式打开
        subkeyNames = software.GetSubKeyNames();   
        //取得该项下所有子项的名称的序列,并传递给预定的数组中   
        foreach (string keyName in subkeyNames) //遍历整个数组   
        {
            if (keyName == fileName) //判断子项的名称   
            {   
                hkml.Close();   
                return true;   
            }   
        }   
            hkml.Close();   
            return false;   
        }


        /// <summary>
        /// 设置程序自启动
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="isAutoRun"></param>
        public static 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);             
            }
            catch
            {
               
                //throw new Exception(ex.ToString());   
            }
            finally
            {
                if (reg != null)
                    reg.Close();
            }
        } 



    }
}
程序编译好之后需要管理员身份运行,否则无效。
posted @ 2011-07-03 18:14  千禧牛  阅读(447)  评论(0)    收藏  举报