WPF Enforce only ONE instance of application

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

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

Thanks.

5条回答
  •  情书的邮戳
    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
    

提交回复
热议问题