【WPF】只允许运行一个程序(单例)

2022/7/13 1:25:50

本文主要是介绍【WPF】只允许运行一个程序(单例),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

有时一个程序需要单例运行,因为涉及到上下位连接,数据库访问,安全性等问题,本博客来探讨如何实现WPF 程序的单例运行。

措施:

利用 System.Threading.Mutex   来实现控制程序的单例运行。

这是MSDN 官方的资料: Mutex : http://msdn.microsoft.com/en-us/library/system.threading.mutex%28v=vs.110%29.aspx 

S1 :在程序结构中找到 App.xaml.cs 文件

在目录中,找到这样两个文件 App.xaml 和 App.xaml.cs

S2:插入以下代码

namespace ElectronicNeedleTherapySystem
{
    /// <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);
            }
 
        }
    }
}

 

其中, namespace ElectronicNeedleTherapySystem 和 mutex = new System.Threading.Mutex(true, "ElectronicNeedleTherapySystem", out ret); 中的

ElectronicNeedleTherapySystem换成自己的工程名称。

S3:在 App.xaml 中设置启动窗体

<Application x:Class="ElectronicNeedleTherapySystem.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="LoginWindow.xaml"
.... />

S4:连续运行两次程序,就可以看到效果

第一次运行程序完全可以运行,第二次运行后,弹出以下提示。

其它方法:

1.通过查找process的方法来控制应用程序启动。

PS:这个方法有bug:在多用户登录后,只有一个用户可以正常启动程序,也就是说,进程是跨用户的。

int processCount = Process.GetProcessesByName("windowWPF").Where(o => o.Id != Process.GetCurrentProcess().Id).Count();
if (processCount > 1)
    Environment.Exit(0);

2. 注意mutex不能被回收,否则就无法发挥作用了。

    bool ret;  
    using (System.Threading.Mutex  mutex = new System.Threading.Mutex(true, "WpfMuerterrrterterttex", out ret))  
    {  
        if (!ret)  
            Environment.Exit(0);  
    }  


这篇关于【WPF】只允许运行一个程序(单例)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程