当前位置: 移动技术网 > IT编程>开发语言>c# > C#代码设置开机启动示例

C#代码设置开机启动示例

2019年07月18日  | 移动技术网IT编程  | 我要评论

在注册表启动项里添加一项,路径:software\microsoft\windows\currentversion\run
或者直接:运行->regedit找到这个路径添加一项。

复制代码 代码如下:

using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.linq;
using system.text;
using system.windows.forms;

using microsoft.win32;

namespace csharpstart
{
public partial class form1 : form
{
public form1()
{
initializecomponent();
}

private void btnset_click(object sender, eventargs e)
{
setautorun(@"d:\csharpstart.exe",true);
}

/// 设置应用程序开机自动运行
/// 应用程序的文件名
/// 是否自动运行,为false时,取消自动运行
/// 设置不成功时抛出异常
public static 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);
}
catch (exception ex)
{
throw new exception(ex.tostring());
}
finally
{
if (reg != null)
reg.close();
}

}
//另外也可以写成服务,不过服务的话一般是在后台执行的,没有程序界面。 柯乐义

}
}

参考:
c# winform程序设置开机启动,当读取配置文件,或者加载图片如果设置的是相对路径时,开机启动时会出现问题(直接运程程序是没问题的)。这是因为开机启动的程序要使用绝对路径,相对路径不行。我们可以通过application .startuppath属性经过处理得到文件的绝对路径问题就解决了。

c# 通过读写注册表来设置开机启动想方法很简单,网上很多:

复制代码 代码如下:

/// 开机启动项


/// 是否启动
/// 启动值的名称
/// 启动程序的路径
public void runwhenstart(bool started, string name, string path)
{
registrykey hklm = registry.localmachine;
registrykey run = hklm.createsubkey(@"software/microsoft/windows/currentversion/run");
if (started == true)
{
try
{
run.setvalue(name, path);
hklm.close();
}
catch//没有权限会异常
{ }
}
else
{
try
{
run.deletevalue(name);
hklm.close();
}
catch//没有权限会异常
{ }
}
}

或者直接:

复制代码 代码如下:

//添加启动
registrykey ms_run = registry.localmachine.opensubkey("software//microsoft//windows//currentversion//run", true);
ms_run.setvalue("mistysoft", application.executablepath.tostring());
//删除启动(设为控,注册表项还在)
registrykey ms_run = registry.localmachine.opensubkey("software//microsoft//windows//currentversion//run", true);
ms_run.setvalue("mistysoft", "");

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网