zoukankan      html  css  js  c++  java
  • WPF防止重复运行实例

    1、方法一

    在app.xaml.cs下添加如下代码:

     /// <summary>  
        /// App.xaml 的交互逻辑  
        /// </summary>  
        public partial class App : Application  
        {  
            System.Threading.Mutex mutex;  
      
            public App()  
            {  
                this.Startup += new StartupEventHandler(App_Startup);  
            }  
      
            void App_Startup(object sender, StartupEventArgs e)  
            {  
                bool ret;  
                mutex = new System.Threading.Mutex(true, "ElectronicNeedleTherapySystem", out ret);  
      
                if (!ret)  
                {  
                    MessageBox.Show("已有一个程序实例运行");  
                    Environment.Exit(0);  
                }  
      
            }  
        }  
    

      二、方法二

    1.通过查找process的方法来控制应用程序启动。
    PS:这个方法有bug:在多用户登录后,只有一个用户可以正常启动程序,也就是说,进程是跨用户的。
    [java] view plain copy
    int processCount = Process.GetProcessesByName("windowWPF").Where(o => o.Id != Process.GetCurrentProcess().Id).Count();  
    if (processCount > 1)  
        Environment.Exit(0);  
    2. 注意mutex不能被回收,否则就无法发挥作用了。
    [java] view plain copy
    bool ret;    
    using (System.Threading.Mutex  mutex = new System.Threading.Mutex(true, "WpfMuerterrrterterttex", out ret))    
    {    
        if (!ret)    
            Environment.Exit(0);    
    }    
    

      

    1.  /// <summary>  
    2.     /// App.xaml 的交互逻辑  
    3.     /// </summary>  
    4.     public partial class App : Application  
    5.     {  
    6.         System.Threading.Mutex mutex;  
    7.   
    8.         public App()  
    9.         {  
    10.             this.Startup += new StartupEventHandler(App_Startup);  
    11.         }  
    12.   
    13.         void App_Startup(object sender, StartupEventArgs e)  
    14.         {  
    15.             bool ret;  
    16.             mutex = new System.Threading.Mutex(true"ElectronicNeedleTherapySystem", out ret);  
    17.   
    18.             if (!ret)  
    19.             {  
    20.                 MessageBox.Show("已有一个程序实例运行");  
    21.                 Environment.Exit(0);  
    22.             }  
    23.   
    24.         }  
    25.     }  
  • 相关阅读:
    28、数组中出现次数超过一半的数字
    27、字符串的排列
    26、二叉搜索树与双向链表
    21、栈的压入、弹出序列
    22、从上往下打印二叉树
    23、二叉搜索树的后序遍历序列
    24、二叉树中和为某一值的路径
    25、复杂链表的复制
    4、简单工厂模式,工厂方法模式,
    基数排序
  • 原文地址:https://www.cnblogs.com/xietianjiao/p/7010370.html
Copyright © 2011-2022 走看看