How can I make sure only one WPF Window is open at a time?

前端 未结 6 994
一整个雨季
一整个雨季 2021-01-14 08:06

I have a WPF window that I am launching from inside of a winform app. I only want to allow once instance of that WPF window to be open at a time, and not warn that user if t

6条回答
  •  天命终不由人
    2021-01-14 08:12

    Rather than try to search for a Window instance, many people use a session- (or system-) wide "Mutex" or a Mutual Exclusion lock. I was going to rewrite one for you, but I found a good codeproject article demonstrating the technique. It's not complex and very simple.

    http://www.codeproject.com/KB/cs/SingleInstanceAppMutex.aspx?msg=2908697

    Sneak peek:

    [STAThread]
    static void Main()
    {
        bool onlyInstance = false;
        Mutex mutex = new Mutex(true, "UniqueApplicationName", out onlyInstance);
        if (!onlyInstance) {
            return;
        }
        Application.Run(new MainForm);
        GC.KeepAlive(mutex);
    }
    

    Hope this helps.

    (edit: of course you'll have to modify this slightly for your particular use-case, but it demos the general idea)

提交回复
热议问题