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

前端 未结 6 901
一整个雨季
一整个雨季 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:33

    Instead of searching the static application objects, you could instead just track this within your window, with a single static variable. Just keep a variable in the window:

    private static frmCaseWpf openWindow = null; // Assuming your class name is frmCaseWpf
    

    When you create a window, either in the initialize routines, or OnLoaded, depending on how you want it to work..:

    partial class frmCaseWpf {
        public frmCaseWpf {
             this.OnLoaded += frmCaseWpf_OnLoaded;
        }
    
        private void frmCaseWpf_OnLoaded(object sender, RoutedEventArgs e)
        {
             if (this.openWindow != null)
             {
                  // Show message box, active this.openWindow, close this
             }
             this.openWindow = this;
        }
    }
    

    If you want this window to be reusable, make sure to set this.openWindow = null; when you close the window, as well.

提交回复
热议问题