C#中Winform自启动一个类搞定: Form1.AutoStart.cs
实现Winform的最小化, 自启动, 任务栏右键退出, 右键显示功能
把此类作为窗体类的部分类添加到项目里面就可以了
using Microsoft.Win32;
using System;
using System.Configuration;
using System.Windows.Forms;
namespace xxxxx {
//实现Winform的最小化, 自启动, 任务栏右键退出, 右键显示功能
//根据 app.config 中的"AutoStart"值设置是否自启动( 1自启动, 其他不自启动 )
partial class Form1
{
#region 最小化,自启动,任务栏右键退出
private System.Windows.Forms.NotifyIcon notifyIcon1;
private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItemShow;
private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItemClose;
//添加任务栏小图标和右键功能和自启动功能
//在构造函数中调用
//入参appCode:应用程序英文名,用来做自启动配置的key,不同的应用需要不一样
private void AddContextMenuAndAutoStart(string appCode)
{
var title = this.Text; //任务栏小图标标题
this.Text += "v1.0." + GetCompileVersion();//动态版本号
this.components = new System.ComponentModel.Container();
var resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components);
this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
this.ToolStripMenuItemShow = new System.Windows.Forms.ToolStripMenuItem();
this.ToolStripMenuItemClose = new System.Windows.Forms.ToolStripMenuItem();
this.contextMenuStrip1.SuspendLayout();
this.contextMenuStrip1.ResumeLayout(false);
//
// notifyIcon1
//
this.notifyIcon1.ContextMenuStrip = this.contextMenuStrip1;
this.notifyIcon1.Icon = new System.Drawing.Icon("Icon.ico"); //任务栏小图标, .ico文件放在项目根目录
this.notifyIcon1.Text = title; //任务栏小图标标题
this.notifyIcon1.Visible = true;
this.notifyIcon1.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.notifyIcon1_MouseDoubleClick);
//
// contextMenuStrip1
//
this.contextMenuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.ToolStripMenuItemShow, this.ToolStripMenuItemClose });
this.contextMenuStrip1.Name = "contextMenuStrip1";
this.contextMenuStrip1.Size = new System.Drawing.Size(101, 48);
//
// ToolStripMenuItemShow
//
this.ToolStripMenuItemShow.Name = "ToolStripMenuItemShow";
this.ToolStripMenuItemShow.Size = new System.Drawing.Size(100, 22);
this.ToolStripMenuItemShow.Text = "显示";
this.ToolStripMenuItemShow.Click += new System.EventHandler(this.ToolStripMenuItemShow_Click);
//
// ToolStripMenuItemClose
//
this.ToolStripMenuItemClose.Name = "ToolStripMenuItemClose";
this.ToolStripMenuItemClose.Size = new System.Drawing.Size(100, 22);
this.ToolStripMenuItemClose.Text = "退出";
this.ToolStripMenuItemClose.Click += new System.EventHandler(this.ToolStripMenuItemClose_Click);
//设置开机自启动
SetAutoStart(appCode);
}
//显示
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.Visible = true;
this.WindowState = FormWindowState.Normal;
this.ShowInTaskbar = true;
}
//显示
private void ToolStripMenuItemShow_Click(object sender, EventArgs e)
{
this.Visible = true;
this.WindowState = FormWindowState.Normal;
this.ShowInTaskbar = true;
}
bool _isClose = false; //是否退出
//最小化
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (!_isClose)
{
e.Cancel = true;
this.Visible = false;
}
}
//退出
private void ToolStripMenuItemClose_Click(object sender, EventArgs e)
{
_isClose = true;
this.Close();
}
//设置开机自启动
private void SetAutoStart(string appCode)
{
try
{
var autoStart = GetAppSetting("AutoStart", "");
if (autoStart == "")
{
SetAppSetting("AutoStart", "1"); //默认自启动
}
if (autoStart == "1")
{
string path = Application.ExecutablePath;
RegistryKey rk = Registry.CurrentUser;
RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
rk2.SetValue(appCode, path); // 不同的APP修改为不同的Key
rk2.Close();
rk.Close();
SetAppSetting("AutoStart", "1");
}
else
{
string path = Application.ExecutablePath;
RegistryKey rk = Registry.CurrentUser;
RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
rk2.DeleteValue(appCode, false);
rk2.Close();
rk.Close();
}
}
catch (Exception ex)
{
}
}
//获取编译日期
public string GetCompileVersion()
{
string OriginVersion = "" + System.IO.File.GetLastWriteTime(this.GetType().Assembly.Location);
int MsgCnt = 0;
string year = "";
string month = "";
string data = "";
for (int i = 0; i < OriginVersion.Length && MsgCnt < 3; i++)
{
char ch = OriginVersion[i];
if (ch >= '0' && ch <= '9')
{
switch (MsgCnt)
{
case 0: year += ch; break;
case 1: month += ch; break;
case 2: data += ch; break;
}
}
else
{
MsgCnt++;
}
}
while (year.Length < 4) year = "0" + year;
while (month.Length < 2) month = "0" + month;
while (data.Length < 2) data = "0" + data;
return year + month + data;
}
//读取App.Config的AppSetting中的参数
public static string GetAppSetting(string key, string defaultValue = "")
{
var val = ConfigurationManager.AppSettings[key];
if (val == null)
{
return defaultValue;
}
return val.ToString();
}
//在*.exe.config文件中appSettings配置节增加一对键、值对
public static void SetAppSetting(string newKey, string newValue)
{
// Open App.Config of executable
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
foreach (string key in ConfigurationManager.AppSettings)
{
if (key == newKey)
{
config.AppSettings.Settings.Remove(newKey);
break;
}
}
// Add an Application Setting.
config.AppSettings.Settings.Add(newKey, newValue);
// Save the changes in App.config file.
config.Save(ConfigurationSaveMode.Modified);
// Force a reload of a changed section.
ConfigurationManager.RefreshSection("appSettings");
}
#endregion
}
}