// 檢查一個自啓動鍵是否存在.
private bool IsValueExist(string KeyValue)
{
RegistryKey hklm = Registry.LocalMachine;
RegistryKey run = hklm.CreateSubKey(@"SOFTWAREMicrosoftWindowsCurrentVersionRun");
string ValueStr1 = null;
try
{
ValueStr1 = (string)run.GetValue(KeyValue);
hklm.Close();
}
catch (Exception Er1)
{
MessageBox.Show(Er1.Message.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (ValueStr1 == null)
return false;
else
return true;
}
// 添加註冊表自啓動鍵
private void SetAutoValue(string KeyValue)
{
// 檢查鍵值是否已經存在,不會重複註冊
bool RT = this.IsValueExist(KeyValue);
if (RT) {
// MessageBox.Show( KeyValue + "已經存在,不再建立");
return;
}
RegistryKey hklm = Registry.LocalMachine;
RegistryKey run = hklm.CreateSubKey(@"SOFTWAREMicrosoftWindowsCurrentVersionRun");
try
{
run.SetValue(KeyValue, Application.ExecutablePath); // 獲得路徑和文件名
MessageBox.Show(" 已經成功設置爲自啓動!!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
hklm.Close();
}
catch (Exception my)
{
MessageBox.Show(my.Message.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// 刪除指定註冊表自啓動鍵
private void DelAutoValue(string KeyValue)
{
// 檢查鍵值是否已經存在,如果已不存在則不操作了
bool RT = this.IsValueExist(KeyValue);
if (!RT)
{
// MessageBox.Show(KeyValue + " 已不存在,無需操作");
return;
}
RegistryKey hklm = Registry.LocalMachine;
RegistryKey run = hklm.CreateSubKey(@"SOFTWAREMicrosoftWindowsCurrentVersionRun");
try
{
// run.SetValue(KeyValue, Application.ExecutablePath); // 獲得路徑和文件名
run.DeleteValue(KeyValue);
MessageBox.Show(" 自啓動已經成功取消!!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
hklm.Close();
}
catch (Exception my)
{
MessageBox.Show(my.Message.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// 主調函數
private void AutoStartSwitch(string KeyNameValue, bool IStart)
{
if (IStart)
this.SetAutoValue(KeyNameValue);
else
this.DelAutoValue(KeyNameValue);
return;
}
/* 都做好以後使用起來就非常方便了:
* AutoStartSwitch("MyClock", true);
* 可以跟一個二態的複選框,或者菜單用在一起
* 很輕易的添加或消除自啓動的註冊項
* 只在操作成功之後,或者出現異常時,纔有提示出現 */
引用: http://blog.zjol.com.cn/tb.asp?id=138670&TBcode=200708211222130Mdq5DCw1A