WinForm開發控制應用程式自啟動功能,winform應用程式
本文主要講述WinForm開發應用程式需要設定自啟動功能,這個也是在實際開發中經常涉及到的,非常實用,所講到的是通過註冊表來控製程序是否自行啟動,具體功能實現上兩張圖,更直觀。
如:
程式設定保持介面實現代碼
using Microsoft.Win32;using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.IO;using System.Linq;using System.Text;using System.Windows.Forms;namespace Tools.App{ public partial class AutoRun : Form { public string KeyName = "Tools資料匯出服務程式"; public AutoRun() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { try { string strName = Application.ExecutablePath; //string strnewName = strName.Substring(strName.LastIndexOf("\\") + 1); if (AutoMenu.Checked) { this.AutoMenu.Checked = true; if (!File.Exists(strName))//指定檔案是否存在 return; Microsoft.Win32.RegistryKey Rkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); if (Rkey == null) { Rkey = Microsoft.Win32.Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"); } Rkey.SetValue(KeyName, strName + " -s");//修改註冊表,使程式開機時自動執行。 MessageBox.Show("程式已設定自啟動,重新啟動電腦後即可生效!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { //修改註冊表,使程式開機時不自動執行。 this.AutoMenu.Checked = false; RegistryKey Rkey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true); if (Rkey == null) { Rkey = Microsoft.Win32.Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"); } Rkey.DeleteValue(KeyName, false); MessageBox.Show("程式已取消自啟動設定!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch//沒有許可權會異常 { MessageBox.Show("請您使用管理員權限開啟應用程式!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void AutoRun_Load(object sender, EventArgs e) { try { string strName = Application.ExecutablePath; if (!File.Exists(strName))//指定檔案是否存在 return; Microsoft.Win32.RegistryKey Rkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); if (Rkey != null) { string val = Rkey.GetValue(KeyName).ToString(); if (val == (strName + " -s")) { this.AutoMenu.Checked = true; } else { this.AutoMenu.Checked = false; } } } catch (Exception ex)//沒有許可權會異常 { //MessageBox.Show(ex.Message); MessageBox.Show("請您使用管理員權限開啟應用程式!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }}
希望以上分享對初學朋友有些協助,謝謝!
更多關注付義方技術部落格:http://blog.csdn.net/fuyifang
或者直接用手機掃描二維碼查看更多博文: