Reputation: 537
How can I detect the click event of the close (X) button at the top right corner of the control box of a form/window? Please note, I don't want to know about CloseReason, FormClosing, FormClosed or stuffs like these, unless they are inevitable. I exactly want to detect if the user clicked the X button of the form. Thanks.
Upvotes: 2
Views: 3856
Reputation: 21
I know this is old thread, but here is a solution.
To get WM_NCLBUTTONUP work, don't call to base WndProc when you get WM_NCLBUTTONDOWN message :
protected override void WndProc(ref Message m)
{
const int WM_NCLBUTTONDOWN = 0x00A1;
const int WM_NCLBUTTONUP = 0x00A2;
const int HTCLOSE = 20;
if (m.Msg == WM_NCLBUTTONDOWN)
{
switch ((int)m.WParam)
{
case HTCLOSE:
// WndProc Form implementation is buggy :
// to receive WM_NCLBUTTONUP message,
// don't call WndProc.
break;
default:
base.WndProc(ref m);
break;
}
}
else
{
if (m.Msg == WM_NCLBUTTONUP)
{
switch ((int)m.WParam)
{
case HTCLOSE:
Trace.WriteLine("Close Button clicked");
Close(); // Optional
break;
}
}
base.WndProc(ref m);
}
}
Upvotes: 2
Reputation: 2220
If you really have a good reason not to use FormClosing, CloseReason, ...
, you can override the window procedure and write something like this:
protected override void WndProc(ref Message m)
{
const int WM_NCLBUTTONDOWN = 0x00A1;
const int HTCLOSE = 20;
if (m.Msg == WM_NCLBUTTONDOWN)
{
switch ((int)m.WParam)
{
case HTCLOSE:
Trace.WriteLine("Close Button clicked");
break;
}
}
base.WndProc(ref m);
}
The details can be found here and here.
Upvotes: 8