在注册表启动项里添加一项,路径:software\microsoft\windows\currentversion\run
或者直接:运行->regedit找到这个路径添加一项。
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//没有权限会异常
{ }
}
}
或者直接:
如对本文有疑问, 点击进行留言回复!!
使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序)
C#实现获取本地内网(局域网)和外网(公网)IP地址的方法分析
网友评论