WPF mutex for single app instance not working

前端 未结 7 1646
梦谈多话
梦谈多话 2020-12-30 01:24

I\'m trying to use the mutex method for only allowing one instance of my app to run. That is - I only want a max of one instance for all users on a machine. I\'ve read throu

相关标签:
7条回答
  • 2020-12-30 02:24

    I was told to implement this mutex approach on an already developed WPF application that we had. The work around to the problem with using override of the OnStart() that I found was in

    App.g.cs
    

    This file is located in

    obj\x86\debug\
    

    and contains the main() function, so you just simply put this piece of code in your main function.

    bool isOnlyInstance = false;
    Mutex m = new Mutex(true, @"WpfSingleInstanceApplication", out isOnlyInstance);
    if (!isOnlyInstance)
    {
        MessageBox.Show("Another Instance of the application is already running.", 
                        "Alert", 
                        MessageBoxButton.OK, 
                        MessageBoxImage.Exclamation);
        return;
    }
    GC.KeepAlive(m);
    

    but for this you need to keep the BUILD ACTION of your app.xaml set to ApplicationDefinition

    NOTE: This might not be the best way, since I'm a beginner. (please tell me if there's something I should change)

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