//RunWhenStart.cs
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;
using System.Windows.Forms;
namespace Walter.K.Wang
{
/// <summary>
///
/// </summary>
public class RunWhenStart
{
/// <summary>
/// 開機自動啟動程序
/// </summary>
/// <param name="Started">true為自動啟動,false為不自動啟動</param>
public static void Run(bool Started)
{
RegistryKey HKLM = Registry.LocalMachine;
RegistryKey Run = HKLM.CreateSubKey(@"SOFTWAREMicrosoftWindowsCurrentVersionRun");
if (Started == true)
{
try
{
Run.SetValue(Application.ProductName, Application.StartupPath + @"" + Application.ProductName + @".exe");
HKLM.Close();
}
catch (Exception Err)
{
throw new Exception(Err.Message);
}
}
else
{
try
{
Run.DeleteValue(Application.ProductName);
HKLM.Close();
}
catch (Exception Err)
{
throw new Exception(Err.Message);
}
}
}
/// <summary>
/// 檢測程序是否自動啟動
/// </summary>
/// <returns>自動啟動為true,不自動啟動為false</returns>
public static bool Getstate()
{
RegistryKey hkml = Registry.LocalMachine;
string[] aimnames;
string keyData = string.Empty;
hkml = Registry.LocalMachine.OpenSubKey(@"SOFTWAREMicrosoftWindowsCurrentVersionRun", true);
aimnames = hkml.GetValueNames();
bool getin = false;
foreach (string aimKey in aimnames)
{
if (aimKey == Application.ProductName)
{
getin = true;
}
}
return getin;
}
}
}
//調用代碼
if (Walter.K.Wang.RunWhenStart.Getstate() == false)
...{
Walter.K.Wang.RunWhenStart.Run(true);
}