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