//
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;
}
}
}
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);
}
if (Walter.K.Wang.RunWhenStart.Getstate() == false )
... {
Walter.K.Wang.RunWhenStart.Run(true);
}