您的位置:首页 > 编程语言 > C#

winform(c#) 开机自动启动程序

2009-09-14 15:22 561 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: