Home > Software design >  C# Wpf App e.Cancel = true unable to use! looking for keep application running in tray
C# Wpf App e.Cancel = true unable to use! looking for keep application running in tray

Time:08-16

I'm unable to use the e.Cancel = true; in c# wpf its returning this error:

CS1061 'FormClosedEventArgs' does not contain a definition for 'Cancel' and no accessible extension method 'Cancel' accepting a first argument of type 'FormClosedEventArgs' could be found (are you missing a using directive or an assembly reference?)

How do I solve it? looking for a quick solution or do I've any way to keep the application running on the tray?

CodePudding user response:

In the XAML designer or in code behind of the Window element you need to add an event handler for the Closing event.

<Window ... Closing="Window_Closing">
    ...
</Window>

Here is the code for a Closing event handler method for WPF applications which will ask the user a question if they really want to close the application.

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    // If user clicks No the application stays open
    if (MessageBox.Show(
        "Are you sure you want to exit the application?",
        "Confirm Exit:",
        MessageBoxButton.YesNo,
        MessageBoxImage.Information) == MessageBoxResult.No)
    {
        e.Cancel = true;
        // Keep application from closing
    }
    // Else the application closes    
}

CodePudding user response:

You likely want to handle the FormClosing event instead - FormClosingEventArgs does have a Cancel property you can use to prevent the window from being closed.

  • Related