C#代碼設(shè)置開機(jī)啟動示例
在注冊表啟動項(xiàng)里添加一項(xiàng),路徑:SOFTWARE\Microsoft\Windows\CurrentVersion\Run
或者直接:運(yùn)行->regedit找到這個(gè)路徑添加一項(xiàng)。
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);
}
/// 設(shè)置應(yīng)用程序開機(jī)自動運(yùn)行
/// 應(yīng)用程序的文件名
/// 是否自動運(yùn)行,為false時(shí),取消自動運(yùn)行
/// 設(shè)置不成功時(shí)拋出異常
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();
}
}
//另外也可以寫成服務(wù),不過服務(wù)的話一般是在后臺執(zhí)行的,沒有程序界面。 柯樂義
}
}
參考:
C# winform程序設(shè)置開機(jī)啟動,當(dāng)讀取配置文件,或者加載圖片如果設(shè)置的是相對路徑時(shí),開機(jī)啟動時(shí)會出現(xiàn)問題(直接運(yùn)程程序是沒問題的)。這是因?yàn)殚_機(jī)啟動的程序要使用絕對路徑,相對路徑不行。我們可以通過Application .StartupPath屬性經(jīng)過處理得到文件的絕對路徑問題就解決了。
C# 通過讀寫注冊表來設(shè)置開機(jī)啟動想方法很簡單,網(wǎng)上很多:
/// 開機(jī)啟動項(xiàng)
/// 是否啟動
/// 啟動值的名稱
/// 啟動程序的路徑
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//沒有權(quán)限會異常
{ }
}
else
{
try
{
Run.DeleteValue(name);
HKLM.Close();
}
catch//沒有權(quán)限會異常
{ }
}
}
或者直接:
//添加啟動
RegistryKey ms_run = Registry.LocalMachine.OpenSubKey("SOFTWARE//Microsoft//Windows//CurrentVersion//Run", true);
ms_run.SetValue("mistysoft", Application.ExecutablePath.ToString());
//刪除啟動(設(shè)為控,注冊表項(xiàng)還在)
RegistryKey ms_run = Registry.LocalMachine.OpenSubKey("SOFTWARE//Microsoft//Windows//CurrentVersion//Run", true);
ms_run.SetValue("mistysoft", "");
相關(guān)文章
基于C#技術(shù)實(shí)現(xiàn)身份證識別功能
這篇文章主要介紹了基于C#技術(shù)實(shí)現(xiàn)身份證識別功能的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-07-07Windows窗體的.Net框架繪圖技術(shù)實(shí)現(xiàn)方法
這篇文章主要介紹了Windows窗體的.Net框架繪圖技術(shù)實(shí)現(xiàn)方法,非常實(shí)用,需要的朋友可以參考下2014-08-08C#使用Json.Net進(jìn)行序列化和反序列化及定制化
在本篇文章里小編給大家分享了關(guān)于C#使用Json.Net進(jìn)行序列化和反序列化及定制化的知識點(diǎn)總結(jié),需要的朋友們參考學(xué)習(xí)下。2019-05-05C#實(shí)現(xiàn)基于IE內(nèi)核的簡單瀏覽器完整實(shí)例
這篇文章主要介紹了C#實(shí)現(xiàn)基于IE內(nèi)核的簡單瀏覽器,較為詳細(xì)的分析了C#實(shí)現(xiàn)瀏覽器的原理與主要功能實(shí)現(xiàn)方法,并附帶完整實(shí)例供大家下載,需要的朋友可以參考下2015-07-07