C# WPF开机自启动和只允许一个程序运行

本文出自:https://www.cnblogs.com/2186009311CFF/p/10024949.html

在App.xaml.cs填充一下内容,即可实现只允许一个运行,且不解锁屏幕的情况下,重启运行。

 public partial class App : Application
    {
        System.Threading.Mutex mutex;
        public App()
        {
            this.Startup += new StartupEventHandler(App_Startup);
            this.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(Application_DispatcherUnhandledException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        }
        private void App_Startup(object sender, StartupEventArgs e)
        {
            bool ret;
            mutex = new System.Threading.Mutex(true, "TestEXEName", out ret);

            if (!ret)
            {
                MessageBox.Show("已有一个客户端正在运行,请先结束原来客户端!");
                Environment.Exit(0);
            }
            #region 设置程序开机自动运行(+注册表项)
            try
            {
                SetSelfStarting(true, "TestEXEName.exe");
            }
            catch (Exception ex)
            {
                WriteLog(ex);
            }
            
            #endregion

        }
        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            if (e.ExceptionObject is Exception)
                WriteLog(e.ExceptionObject);
            else
                WriteLog(e);
        }

        private void Application_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            if (e.Exception is Exception)
                WriteLog(e.Exception);
            else
                WriteLog(e);
        }

        #region 注册表开机自启动


        /// <summary>
        /// 开机自动启动
        /// </summary>
        /// <param name="started">设置开机启动,或取消开机启动</param>
        /// <param name="exeName">注册表中的名称</param>
        /// <returns>开启或停用是否成功</returns>
        public bool SetSelfStarting(bool started, string exeName)
        {
            RegistryKey key = null;
            try
            {

                string exeDir = System.Windows.Forms.Application.ExecutablePath;
                //RegistryKey HKLM = Registry.CurrentUser;
                //key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);//打开注册表子项
                key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);//打开注册表子项

                if (key == null)//如果该项不存在的话,则创建该子项
                {
                    key = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
                }
                if (started)
                {
                    try
                    {
                        object ob = key.GetValue(exeName, -1);

                        if (!ob.ToString().Equals(exeDir))
                        {
                            if (!ob.ToString().Equals("-1"))
                            {
                                key.DeleteValue(exeName);//取消开机启动
                            }
                            key.SetValue(exeName, exeDir);//设置为开机启动
                        }
                        key.Close();

                    }
                    catch (Exception ex)
                    {
                        WriteLog(ex);
                        return false;
                    }
                }
                else
                {
                    try
                    {
                        key.DeleteValue(exeName);//取消开机启动
                        key.Close();
                    }
                    catch (Exception ex)
                    {
                        WriteLog(ex);
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                WriteLog(ex);
                if (key != null)
                {
                    key.Close();
                }
                return false;
            }
        }

        #endregion

        private  void WriteLog(object exception)
        {
            Exception ex = exception as Exception;

            using (FileStream fs = File.Open(".//ErrorLog.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                fs.Seek(0, SeekOrigin.End);
                byte[] buffer = Encoding.Default.GetBytes("-------------------------------------------------------\r\n");
                fs.Write(buffer, 0, buffer.Length);

                buffer = Encoding.Default.GetBytes(DateTime.Now.ToString() + "\r\n");
                fs.Write(buffer, 0, buffer.Length);

                if (ex != null)
                {
                    buffer = Encoding.Default.GetBytes("成员名: " + ex.TargetSite + "\r\n");
                    fs.Write(buffer, 0, buffer.Length);

                    buffer = Encoding.Default.GetBytes("引发异常的类: " + ex.TargetSite.DeclaringType + "\r\n");
                    fs.Write(buffer, 0, buffer.Length);

                    buffer = Encoding.Default.GetBytes("异常信息: " + ex.Message + "\r\n");
                    fs.Write(buffer, 0, buffer.Length);

                    buffer = Encoding.Default.GetBytes("引发异常的程序集或对象: " + ex.Source + "\r\n");
                    fs.Write(buffer, 0, buffer.Length);

                    buffer = Encoding.Default.GetBytes("栈:" + ex.StackTrace + "\r\n");
                    fs.Write(buffer, 0, buffer.Length);
                }
                else
                {
                    buffer = Encoding.Default.GetBytes("应用程序错误: " + exception.ToString() + "\r\n");
                    fs.Write(buffer, 0, buffer.Length);
                }
            }

        }
    }

 

 

 

参考:https://bbs.csdn.net/topics/390951628?page=1

https://www.cnblogs.com/gaobing/p/gaobing.html

转载于:https://www.cnblogs.com/2186009311CFF/p/10024949.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值