Search code examples
c#wpfkeyboard-shortcuts

Disable Alt+F4 in UserControl


i have some user control and i want to disable Alt + F4 oportunity for the end user. When my User Control shows, there is opportunity to close it with Alt + F4, then program goes to base class in the method:

protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
    //Content = null; // Remove child from logical parent - for reusing purposes
    this.RemoveLogicalChild(Content); //this works faster
    base.OnClosing(e);
    { GC.Collect(); };
}

What i must do here or somewhere else, to do disable my user control closing on Alt + F4?


Solution

  • To be sure, I would really question this as a Best Practice. However, if you really want to do this, then you need to prevent the window containing the UserControl from closing.

    The easiest way to do this is to set a DependencyProperty on your UserControl that is simply a Boolean that flags whether the container can be closed. You would only set this to true when you want it to actually close (you probably already have a button or something that you are using now to close the control).

    public Boolean AllowClose
    {
        get { return (Boolean)GetValue(AllowCloseProperty); }
        set { SetValue(AllowCloseProperty, value); }
    }
    
     public static readonly DependencyProperty AllowCloseProperty =
        DependencyProperty.Register("AllowClose", typeof(Boolean), 
        typeof(MyUserControl), new UIPropertyMetadata(false));
    

    Then, in the windows Closing event, you would check for that property to be set to true. If it is not, then you would set e.Cancel = true;

    Using your example:

       protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
       {
        if (! myUserControl.AllowClose)
        {
            MessageBox.Show("Even though most Windows allow Alt-F4 to close, I'm not letting you!");
            e.Cancel = true;
        }
        else
        {
            //Content = null; // Remove child from parent - for reuse
            this.RemoveLogicalChild(Content); //this works faster
            base.OnClosing(e);
            { GC.Collect(); };
        }
    }