python开机自启动代码_c#教程之C#代码设置开机启动示例

https://www.xin3721.com/eschool/

在注册表启动项里添加一项,路径:SOFTWARE\Microsoft\Windows\CurrentVersion\Run

或者直接:运行->regedit找到这个路径添加一项。

1I44551N-0.jpg?201406113448

复制代码 代码如下:

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", "");

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值