C# mouse events on a panel don't apply to objects in panel

2.2k views Asked by At

I am working on a simple C# program that allows the user to use the mouse to move simple controls (Buttons, textareas, etc), similar to a visual designer like visual studio. The controls are contained in a panel and they all work as expected. However, when I call MouseDown() on the panel the controls are contained in, the event only fires when clicking on an empty part of the panel, not when I click on a Control contained within the form.

Here is my MouseDown() Code:

 private void splitContainer2_Panel2_MouseDown(object sender, MouseEventArgs e)
        {

            Console.WriteLine("MOUSE GRABBED");
            ...

            //More code that uses the X and Y co-ords of the mouse to check which
            //Control is selected
            ...
        }

As you can see it is very straightforward. The writeLine() is not triggered when I click on a control.

I have looked at questions such as: ignore mouse event on label inside panel To no avail.

Any help would be appreciated, even a better method to do what I am trying to acomplish.

2

There are 2 answers

0
user3427165 On BEST ANSWER

Instead of using a MouseDown() event for the panel, why not trying to use the same one for every object? Based on what you are trying to do, add the following code:

Where you create each form element:

nameOfElement.MouseDown += new System.Windows.Forms.MouseEventHandler(this.splitContainer2_Panel2_Objects_MouseDown);

The mouse down method:

Control ctrl = (Control)sender;
Console.WriteLine("Moused down on: " + ctrl.Name);
//Code to manipulate mouse down

Hope this helps!

2
Ming Slogar On

Use PreviewMouseDown. The WPF hit testing engine will not raise events on parent elements if the child element absorbs the event.