C#编写的windows程序随系统启动

url:http://www.cnblogs.com/emanlee/archive/2009/08/31/1557380.html

设置某程序随系统启动自动运行,取消自动运行。 使用到using Microsoft.Win32;名称空间。

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); 
        MessageBox.Show("设定成功!","提示"); 
    }   
    catch  
    {   
        //throw new Exception(ex.ToString());   
    }   
    finally  
    {   
        if (reg != null)   
        reg.Close();   
    }   
 }

 

 

posted @ 2013-08-31 00:21  水果饮料  阅读(337)  评论(0)    收藏  举报