WPF Enforce only ONE instance of application

故事扮演 提交于 2019-11-28 16:42:34

问题


How do I allow only one instance of a WPF application to run?

Thanks.


回答1:


http://blogs.microsoft.co.il/blogs/arik/archive/2010/05/28/wpf-single-instance-application.aspx

Doesn't require VB.DLL as some other examples advise. Has WPF sample code. Passes any cmd line args to initial instance.




回答2:


Try this: Single instance application. Ive used the second method and it works fine.




回答3:


I use this helper method and call it from the application.startup event

    Public Sub ForceSingleInstanceApplication()
        'Get a reference to the current process
        Dim MyProc As Process = Process.GetCurrentProcess

        'Check how many processes have the same name as the current process
        If (Process.GetProcessesByName(MyProc.ProcessName).Length > 1) Then
            'If there is more than one, it is already running
            MsgBox("Application is already running", MsgBoxStyle.Critical, My.Application.Info.Title) 'Reflection.Assembly.GetCallingAssembly().GetName().Name)
            ' Terminate this process and give the operating system the specified exit code.
            Environment.Exit(-2)
            Exit Sub
        End If
    End Sub



回答4:


Check out this solution: Allowing only one instance of a WPF application to execute

This not only enforces one instance of an application, but it also gives your current application focus when an additional instance of an application is ran. My mutex solution to restricting one instance is actually different from the above link, but I liked the "focus" element to this solution.




回答5:


User sobelito linked this post, which has the following update. What it says is that for an updated resource you should use Windows 7 Taskbar Single Instance, which if you look into the source will allow you to do what you need.

You can use the SingleInstance c# project. It also contains samples for both WinForms and WPF.

Note that it's also released under the Apache 2.0 license, unlike Arik's Poznanski post in the Microsoft Blog, which is (IANAL, AFAIK) not commercially available.



来源:https://stackoverflow.com/questions/414642/wpf-enforce-only-one-instance-of-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!