BFree
BFree

Reputation: 103740

How can you get the coordinates of the "X" button in a window?

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?

Upvotes: 0

Views: 1834

Answers (2)

Meta-Knight
Meta-Knight

Reputation: 17845

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.

Upvotes: 3

Gibsnag
Gibsnag

Reputation: 1087

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

Upvotes: 0

Related Questions