WPF Enforce only ONE instance of application

后端 未结 5 512
温柔的废话
温柔的废话 2021-01-30 17:12

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

Thanks.

相关标签:
5条回答
  • 2021-01-30 17:30

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

    0 讨论(0)
  • 2021-01-30 17:39

    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.

    0 讨论(0)
  • 2021-01-30 17:43

    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.

    0 讨论(0)
  • 2021-01-30 17:43

    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
    
    0 讨论(0)
  • 2021-01-30 17:48

    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.

    0 讨论(0)
提交回复
热议问题