定义一个服务 static void Main() { System.ServiceProcess.ServiceBase[] ServicesToRun; // Change the following line to match. ServicesToRun = new System.ServiceProcess.ServiceBase[] { new MyNewService() }; System.ServiceProcess.ServiceBase.Run(ServicesToRun); }
string msg = string.Empty;
if (chkAutoRun.Checked == true)
{
msg = CommonMethod.AutoRun(true) == true ? "设置开机启动成功!" : "设置开机启动失败!";
}
else if (CommonMethod.AutoRun(false) == true)
{
msg = "取消开机启动成功!";
} /// <summary>
/// 设置程序开机启动或取消开机启动
/// </summary>
/// <param name="param">true开机启动,flase取消开机启动</param>
/// <returns></returns>
public static bool AutoRun(bool param)
{
string strName = Application.ExecutablePath;
string strNewName = strName.Substring(strName.LastIndexOf("\\") + 1, strName.LastIndexOf(".") - strName.LastIndexOf("\\") - 1);
//指定文件是否存在
if (!System.IO.File.Exists(strName))
return false;
Microsoft.Win32.RegistryKey rkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (rkey == null)
rkey = Microsoft.Win32.Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
//修改注册表
try
{
if (param == true)
rkey.SetValue(strNewName, strName);//设置开机启动
else
rkey.DeleteValue(strNewName);//取消开机启动
return true;
}
catch
{
}
return false;
}
我后来把路径改正确了,也写不进去。在 64位系统下,如果是x86的进程去写注册表会自动写到Wow6432Node下面
//获取执行该方法的程序集,并获取该程序集的文件路径(由该文件路径可以得到程序集所在的目录)
string thisExecutablePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
//SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run注册表中这个路径是开机自启动的路径
Microsoft.Win32.RegistryKey Rkey =
Microsoft.Win32.Registry.LocalMachine.CreateSubKey
("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
Rkey.SetValue(appName, thisExecutablePath);
Rkey.Close();
之前用这个可以写入的
http://blog.csdn.net/jiankunking/article/details/18219573
{
System.ServiceProcess.ServiceBase[] ServicesToRun;
// Change the following line to match.
ServicesToRun = new System.ServiceProcess.ServiceBase[]
{ new MyNewService() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}