当前位置:首页 > Windows程序 > 正文

WinForm开发控制应用程序自启动功能

2021-05-25 Windows程序

本文主要讲述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); } } } }

希望以上分享对初学朋友有些帮助,谢谢!
更多关注付义方技术博客:
或者直接用手机扫描二维码查看更多博文:

技术分享

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/70755.html