Home > Back-end >  red close button event
red close button event

Time:10-29

What is the event that a function will be triggered when the user is clicking on the red close button. I need to create a little lets name it log item when thiss happens in a txt file.

I searched but didn't find any solution

private void Window_Closing1(object sender, System.Windows.Forms.FormClosingEventArgs e)
{

}

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

}

CodePudding user response:

There is no event that is linked to the user clicking that Close button specifically. A form has Closing and Closed events, but they're pretty much obsolete these days and have been superseded by the FormClosing and FormClosed events.

FormClosing is raised before the form closes and allows you to prevent it closing. FormClosed is raised after the form has closed. Both events provide an e.CloseReason property that gives you more specific information on how the form was closed. That property would be UserClosing if the user clicked the Close button on the title bar, but there are other methods that would result in the same value.

CodePudding user response:

As you may know, there is no built-in event in the Form class. However, you can intercept the WM_SYSCOMMAND message on Form.WndProc(ref Message m) and check if the Message.WParam is equal to SC_CLOSE to catch the event at which the window close button is clicked. Optionally, you can have a special event named CloseButtonClick and raise the event.

using System;
using System.Windows.Forms;

namespace ExampleApp
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }
        public event EventHandler CloseButtonClick;

        private const int WM_SYSCOMMAND = 0x0112;
        private IntPtr SC_CLOSE = new IntPtr(0xF060);

        // When you inherite from this class, for a good practice, you should override this method to catch the event with calling base definition.
        protected virtual void OnCloseButtonClick(object sender, EventArgs args)
        {
            if(CloseButtonClick != null)
                CloseButtonClick(sender, args);
        }
        protected override void WndProc(ref Message m)
        {
            if(m.Msg == WM_SYSCOMMAND)
            {
                if (m.WParam == SC_CLOSE)
                    OnCloseButtonClick(this, new EventArgs());
            }
            base.WndProc(ref m);
        }

    }
}
  • Related