C#代碼設(shè)置開機啟動示例
在注冊表啟動項里添加一項,路徑: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);
}
/// 設(shè)置應(yīng)用程序開機自動運行
/// 應(yīng)用程序的文件名
/// 是否自動運行,為false時,取消自動運行
/// 設(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è)置開機啟動,當讀取配置文件,或者加載圖片如果設(shè)置的是相對路徑時,開機啟動時會出現(xiàn)問題(直接運程程序是沒問題的)。這是因為開機啟動的程序要使用絕對路徑,相對路徑不行。我們可以通過Application .StartupPath屬性經(jīng)過處理得到文件的絕對路徑問題就解決了。
C# 通過讀寫注冊表來設(shè)置開機啟動想方法很簡單,網(wǎ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è)為控,注冊表項還在)
RegistryKey ms_run = Registry.LocalMachine.OpenSubKey("SOFTWARE//Microsoft//Windows//CurrentVersion//Run", true);
ms_run.SetValue("mistysoft", "");
相關(guān)文章
Windows窗體的.Net框架繪圖技術(shù)實現(xiàn)方法
這篇文章主要介紹了Windows窗體的.Net框架繪圖技術(shù)實現(xiàn)方法,非常實用,需要的朋友可以參考下2014-08-08C#實現(xiàn)基于IE內(nèi)核的簡單瀏覽器完整實例
這篇文章主要介紹了C#實現(xiàn)基于IE內(nèi)核的簡單瀏覽器,較為詳細的分析了C#實現(xiàn)瀏覽器的原理與主要功能實現(xiàn)方法,并附帶完整實例供大家下載,需要的朋友可以參考下2015-07-07