none
Cannot set Visibility or call Show or ShowDialog after window has closed.

    Question

  • System.InvalidOperationException was unhandled
      Message="Cannot set Visibility or call Show or ShowDialog after window has closed."

     

    I get this exception after running .Show() on a Window that has been closed. I have searched for a solution and the only one i can find is to hide the window instead of closing it. I can not make a new instance of my window so I guess I have to hide it instead. I'd like not to implement the hiding in the window but rather let another class handle all windows that closes. When I implement the window.hide() method like that it throws the same exception as above. My code is like this:

     

    public partial class App : System.Windows.Application

    {

    private Window1 w1 = new Window1();

    protected override void OnStartup(StartupEventArgs e)

    {

    base.ShutdownMode = ShutdownMode.OnExplicitShutdown;

    EventManager.RegisterClassHandler(typeof(Window), Window.LoadedEvent, new RoutedEventHandler(WindowLoaded));

    NotifyIcon notifyIcon = new NotifyIcon();

    notifyIcon.Icon = TestNotifyIcon.Properties.Resources.icon2;

    System.Windows.Forms.MenuItem menuItem1 = new System.Windows.Forms.MenuItem("Window1", new System.EventHandler(menuItem1_Click));

    System.Windows.Forms.MenuItem menuItem3 = new System.Windows.Forms.MenuItem("Exit", new System.EventHandler(menuItem3_Click));

    System.Windows.Forms.MenuItem[] items = { menuItem1, menuItem3 };

    System.Windows.Forms.ContextMenu cm = new System.Windows.Forms.ContextMenu(items);

    notifyIcon.ContextMenu = cm;

    notifyIcon.Visible = true;

    base.OnStartup(e);

    }

     

    //Window is loaded

    void WindowLoaded(object sender, RoutedEventArgs e)

    {

    Window w = sender as Window;

    if (w != null)

    {

    w.Closing += new System.ComponentModel.CancelEventHandler(w_Closing);

    }

    }

    //Window is closing

    void w_Closing(object sender, System.ComponentModel.CancelEventArgs e)

    {

    Window w = sender as Window;

    if (w != null)

    {

    e.Cancel = true;

    w.Hide();  //Crash

    }

    }

    //Show window

    void menuItem1_Click(object sender, EventArgs e)

    {

    w1.Show(); //Crash

    }

    //Exit application

    void menuItem3_Click(object sender, EventArgs e)

    {

    this.Shutdown();

    }

    }

     

     

    Project availible at: http://www.fkaudio.com/temp/TestNotifyIcon.zip

     

     

     

    Thanks!

     

    Lina

    Tuesday, September 11, 2007 7:54 AM

All replies