views:

421

answers:

2

For one reason or another, I have a need to detect when the user actually clicked on the X button. What I have so far is this:

    protected override void WndProc(ref Message m)
    {
        if (m.Msg == (int)0xa1) //WM_NCLBUTTONDOWN
        {
            Point p = new Point((int)m.LParam);
            p = this.PointToClient(p);
            if (p.X > 680)
            {
                //do what I need to do...
            }
        }

        base.WndProc(ref m);
    }

Basically, I look out for the "WM_NCLBUTTONDOWN" message which is the Mouse Click on the Non Client Area of a window. Then, I get the X and Y coordinates from the LParam and finally I convert it to Screen Coordinates. So at this point, I know that the user clicked on the non client area and I know where on the Form.

My question is, how can I tell if these coordinates are on the X button. For now, I'm hardcoding 680 because that's what works in the current size of the window (it's not sizable) but the problem is I'm using Windows 7 which has bigger X buttons than XP, so obviously hardocding isn't a viable option. Furthermore, I haven't even coded for the Y coordinates, so if someone clicks on the right edge of the window, that triggers that code as well. So... anyone have any ideas?

+3  A: 

Let's say you have an OK and a Cancel button, why don't you just set a value when one of these buttons is clicked. Then on the form's Closing event, if this value is not set, you know the X button has been clicked. Unless there are other ways of closing the form I'm not aware of...

Edit:

Instead of using a global boolean, you could change the DialogResult property of the form on your button clicks. I'm not sure what is the DialogResult value when you click the X button though, you'll have to try it.

Meta-Knight
Ok, I just re-read your post, and I see what you're saying now. I didn't really want to have to keep booleans around for the buttons that trigger validation. I may end up having to resort to this if there is no other solution. For now I'll keep this question open though, if no one can provide a solution, I'll mark this as accepted. Thanks!. +1
BFree
keeping a flag for needing to validate is hacky, but less hacky than what the OP is originally asking to do. +1
Tim
You could also use DialogResult instead of booleans, check my edit!
Meta-Knight
Set the DialogResult of the form to a default of Cancel in the Load event of the form. Let the default be to not validate since most actions do not validate the form. Then all the other ways of closing should use that.
toast
A: 

If you test for the WM_NCHITTEST message that should tell you when the mouse is hovering over the close button.

Gibsnag