C# 设置程序启动项

托盘图标设置

新建一个NotifyIcon,会在托盘处显示一个图标。

NotifyIcon.Icon可以直接设置一个ico图片,也可以延用原有程序的图标。

notifyIcon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(Application.ExecutablePath);

 1     private NotifyIcon _notifyIcon;
 2     private void SetNotifyIcon()
 3     {
 4         this._notifyIcon = new NotifyIcon();
 5         this._notifyIcon.BalloonTipText = "翻译小工具";
 6         this._notifyIcon.ShowBalloonTip(2000);
 7         this._notifyIcon.Text = "集成金山、有道非官方数据的翻译工具";
 8         this._notifyIcon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(System.Windows.Forms.Application.ExecutablePath);
 9         this._notifyIcon.Visible = true;
10         //打开菜单项
11         MenuItem open = new MenuItem("打开");
12         open.Click += new EventHandler(ShowMainWindow);
13         //退出菜单项
14         MenuItem exit = new MenuItem("退出");
15         exit.Click += new EventHandler(Close);
16         //关联托盘控件
17         MenuItem[] childen = new MenuItem[] { open, exit };
18         _notifyIcon.ContextMenu = new ContextMenu(childen);
19 
20         this._notifyIcon.MouseDoubleClick += new MouseEventHandler((o, e) =>
21         {
22             if (e.Button == MouseButtons.Left) ShowMainWindow(o, e);
23         });
24     }
25 
26     private void ShowMainWindow(object sender, EventArgs e)
27     {
28         _mainWindow.Visibility = Visibility.Visible;
29         _mainWindow.ShowInTaskbar = true;
30         _mainWindow.Activate();
31     }
32 
33     private void Close(object sender, EventArgs e)
34     {
35         Application.Current.Shutdown();
36     }

 

禁用多进程启动

1     //禁止双进程
2     bool canCreateNew;
3     using (System.Threading.Mutex m = new System.Threading.Mutex(true, System.Windows.Forms.Application.ProductName, out canCreateNew))
4     {
5         if (!canCreateNew)
6         {
7             this.Shutdown();
8         }
9     }

删除原有进程

 1     /// <summary>
 2     /// 删除原有进程
 3     /// </summary>
 4     /// <param name="processName"></param>
 5     private void KillProcess(string processName)
 6     {
 7         try
 8         {
 9             //删除所有同名进程
10             Process currentProcess = Process.GetCurrentProcess();
11             var processes = Process.GetProcessesByName(processName).Where(process => process.Id != currentProcess.Id);
12             foreach (Process thisproc in processes)
13             {
14                 thisproc.Kill();
15             }
16         }
17         catch (Exception ex)
18         {
19         }
20     }

 

设置开机自启动

 关于C#开机自动启动程序的方法,修改注册表:

       1. HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run

       2.HKEY_Current_User\Software\Microsoft\Windows\CurrentVersion\Run

系统有默认选择注册表位置。如果LocalMachine设置异常,则可以在CurrentUser中设置开机启动项。

当然通过管理员权限,也是可以在LocalMachine设置的。

        private void SetAppAutoRun(bool autoRun)
        {
            try
            {
                string executablePath = System.Windows.Forms.Application.ExecutablePath;
                string exeName = Path.GetFileNameWithoutExtension(executablePath);
                SetAutoRun(autoRun, exeName, executablePath);
            }
            catch (Exception e)
            {
            }
        }
        private bool SetAutoRun(bool autoRun, string exeName, string executablePath)
        {
            bool success = SetAutoRun(Registry.LocalMachine, autoRun, exeName, executablePath);
            if (!success)
            {
                success = SetAutoRun(Registry.CurrentUser, autoRun, exeName, executablePath);
            }
            return success;
        }
        private bool SetAutoRun(RegistryKey rootKey, bool autoRun, string exeName, string executablePath)
        {
            try
            {
                RegistryKey autoRunKey = rootKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
                if (autoRunKey == null)
                {
                    autoRunKey = rootKey.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
                }
                if (autoRunKey != null)
                {
                    if (autoRun) //设置开机自启动  
                    {
                        autoRunKey.SetValue(exeName, $"\"{executablePath}\" /background");
                    }
                    else //取消开机自启动  
                    {
                        autoRunKey.DeleteValue(exeName, false);
                    }
                    autoRunKey.Close();
                    autoRunKey.Dispose();
                }
            }
            catch (Exception e)
            {
                rootKey.Close();
                rootKey.Dispose();
                return false;
            }
            rootKey.Close();
            rootKey.Dispose();
            return true;
        }

 App.cs中完整代码:

  1     public partial class App : Application
  2     {
  3         MainWindow _mainWindow;
  4         public App()
  5         {
  6             KillProcess(System.Windows.Forms.Application.ProductName);
  7 
  8             SetAppAutoRun(true);
  9 
 10             Startup += App_Startup;
 11         }
 12 
 13         private void App_Startup(object sender, StartupEventArgs e)
 14         {
 15             _mainWindow = new MainWindow();
 16             SetNotifyIcon();
 17         }
 18 
 19         #region 托盘图标
 20 
 21         private NotifyIcon _notifyIcon;
 22         private void SetNotifyIcon()
 23         {
 24             this._notifyIcon = new NotifyIcon();
 25             this._notifyIcon.BalloonTipText = "翻译小工具";
 26             this._notifyIcon.ShowBalloonTip(2000);
 27             this._notifyIcon.Text = "集成金山、有道非官方数据的翻译工具";
 28             this._notifyIcon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(System.Windows.Forms.Application.ExecutablePath);
 29             this._notifyIcon.Visible = true;
 30             //打开菜单项
 31             MenuItem open = new MenuItem("打开");
 32             open.Click += new EventHandler(ShowMainWindow);
 33             //退出菜单项
 34             MenuItem exit = new MenuItem("退出");
 35             exit.Click += new EventHandler(Close);
 36             //关联托盘控件
 37             MenuItem[] childen = new MenuItem[] { open, exit };
 38             _notifyIcon.ContextMenu = new ContextMenu(childen);
 39 
 40             this._notifyIcon.MouseDoubleClick += new MouseEventHandler((o, e) =>
 41             {
 42                 if (e.Button == MouseButtons.Left) ShowMainWindow(o, e);
 43             });
 44         }
 45 
 46         private void ShowMainWindow(object sender, EventArgs e)
 47         {
 48             _mainWindow.Visibility = Visibility.Visible;
 49             _mainWindow.ShowInTaskbar = true;
 50             _mainWindow.Activate();
 51         }
 52 
 53         private void Close(object sender, EventArgs e)
 54         {
 55             Application.Current.Shutdown();
 56         }
 57 
 58         #endregion
 59 
 60         #region 删除原有进程
 61 
 62         /// <summary>
 63         /// 删除原有进程
 64         /// </summary>
 65         /// <param name="processName"></param>
 66         private void KillProcess(string processName)
 67         {
 68             try
 69             {
 70                 //删除所有同名进程
 71                 Process currentProcess = Process.GetCurrentProcess();
 72                 var processes = Process.GetProcessesByName(processName).Where(process => process.Id != currentProcess.Id);
 73                 foreach (Process thisproc in processes)
 74                 {
 75                     thisproc.Kill();
 76                 }
 77             }
 78             catch (Exception ex)
 79             {
 80             }
 81         }
 82 
 83         #endregion
 84 
 85         #region 开机自启动
 86 
 87         private void SetAppAutoRun(bool autoRun)
 88         {
 89             try
 90             {
 91                 string executablePath = System.Windows.Forms.Application.ExecutablePath;
 92                 string exeName = Path.GetFileNameWithoutExtension(executablePath);
 93                 SetAutoRun(autoRun, exeName, executablePath);
 94             }
 95             catch (Exception e)
 96             {
 97             }
 98         }
 99         private bool SetAutoRun(bool autoRun, string exeName, string executablePath)
100         {
101             bool success = SetAutoRun(Registry.CurrentUser, autoRun, exeName, executablePath);
102             if (!success)
103             {
104                 success = SetAutoRun(Registry.LocalMachine, autoRun, exeName, executablePath);
105             }
106             return success;
107         }
108         private bool SetAutoRun(RegistryKey rootKey, bool autoRun, string exeName, string executablePath)
109         {
110             try
111             {
112                 RegistryKey autoRunKey = rootKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
113                 if (autoRunKey == null)
114                 {
115                     autoRunKey = rootKey.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
116                 }
117                 if (autoRunKey != null)
118                 {
119                     if (autoRun) //设置开机自启动  
120                     {
121                         autoRunKey.SetValue(exeName, $"\"{executablePath}\" /background");
122                     }
123                     else //取消开机自启动  
124                     {
125                         autoRunKey.DeleteValue(exeName, false);
126                     }
127                     autoRunKey.Close();
128                     autoRunKey.Dispose();
129                 }
130             }
131             catch (Exception e)
132             {
133                 rootKey.Close();
134                 rootKey.Dispose();
135                 return false;
136             }
137             rootKey.Close();
138             rootKey.Dispose();
139             return true;
140         }
141 
142         #endregion
143     }
View Code

 

posted @ 2018-11-01 19:51  唐宋元明清2188  阅读(1386)  评论(2编辑  收藏  举报