catch the close button event on a windows form

In order to catch the close button event of the form we need to override the WndProc method.

Code:

public partial class MyForm : Form
{
    public MyForm()
    {
        InitializeComponent();
    }

    protected override void WndProc(ref Message M)
    {
        const int WM_SYSCOMMAND = 0x112;
        const int SC_CLOSE = 0xf060;

        if (M.Msg == WM_SYSCOMMAND & M.WParam.ToInt32() == SC_CLOSE)
        {
            // User clicked the X - close button
            // Any code handling goes here:

            return;
        }

        base.WndProc(ref M);
    }
}
Advertisements

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: