.net, C#, Code, Microsoft, WPF

Hide a window instead of closing it in WPF

I wanted to give WPF a try and was creating a timer application which will pop up a window once a while. But what I wanted was for the application to keep running in the tray even when its closed. The following code does NOT work in WPF for some reason:

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            Window.Visibility = !Window.Visibility;
        }

 

In order to hide a closing window in WPF, this is what needs to be done:

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {

            //Do some stuff here 

            //Hide Window
            Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, (DispatcherOperationCallback)delegate(object o)
            {
                Hide();
                return null;
            }, null);

            //Do not close application
            e.Cancel = true;

        }

Advertisements

3 thoughts on “Hide a window instead of closing it in WPF

  1. Hi, Balaji.
    The code works fine:
    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
    e.Cancel = true;
    Visibility = Visibility.Collapsed;
    }
    Invoking is only required if multithreading model is used.
    Another problem is that you never close your application, because with such code you can not close the window.

  2. This also works. Thanks for the code = )

    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
    e.Cancel = true;
    this.Hide();
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s