Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect click out of the control in c#

Tags:

For begin I want to describe my problem for you.

I want to show huge number of records in something like combobox, but because combobox isn't a good solution for displaying such huge number of data hence I simulate combobox behaviour with DataGridView.

Now my problem is when user click out of DataGridView , DataGridView should be closed(like combobox when it isn't collapsed or dropped). but there is a lot of other control on the form and I cant handle click event of all of them to detect that out of DataGridView has been clicked.

to sum up I look for a simple solution for invisible DataGridView if user click outta that .

at the end I know a vague awareness of MouseCapture property of controls but I cant work with that and I dont know how can I use that for handle my desire.I am appreciate you if you can help me for using MouseCapture for solving this problem or giving another solution.

thanks for you

like image 781
hamed Avatar asked Jan 09 '17 20:01

hamed


1 Answers

A custom control should make this fairly simple, especially if this is a top-level control (i.e. directly in your main window). You can listen for click events on the parent object and use the ClientRectangle property to determine if the click was outside the DataGridView.

Here's a basic example:

class MyDataGridView : DataGridView, IMessageFilter {
    public MyDataGridView() {
        Application.AddMessageFilter(this);
        this.HandleDestroyed += (sender, args) => Application.RemoveMessageFilter(this);
    }

    public bool PreFilterMessage(ref Message m) {
        if (m.Msg == 0x201) {
            if (!ClientRectangle.Contains(PointToClient(Control.MousePosition))) {
                Hide();
            }
        }
        return false;
    }
}
like image 113
Peter Avatar answered Oct 14 '22 02:10

Peter