User Controls in C # Windows Forms Mouse Event Question

I have a mouseenter and mouseleave event for a Panel control that changes the inverse color when the mouse enters and returns to white when it leaves.

I have control over the Label inside this panel, but when the mouse enters the Label control, a mouseleave event occurs for the panel.

This makes sense, but how can I keep the back of the panel the same way when the mouse is in its area, if other controls do not affect it?

+4
source share
4 answers

You can use GetChildAtPoint () to determine if the mouse is over the child control.

private void panel1_MouseLeave(object sender, EventArgs e) { if (panel1.GetChildAtPoint(panel1.PointToClient(MousePosition)) == null) { panel1.BackColor = Color.Gray; } } 

If the control is not actually a child of the control, you can still use MousePosition and PointToScreen to determine if the mouse is still within the control.

 private void panel1_MouseLeave(object sender, EventArgs e) { Rectangle screenBounds = new Rectangle(this.PointToScreen(panel1.Location), panel1.Size); if (!screenBounds.Contains(MousePosition)) { panel1.BackColor = Color.Gray; } } 
+4
source

Adding an event to an contained control means that if you want to add another control to the panel, you also need to go through this exercise.

Adding an event to the parent control means that as soon as you want to use the panel elsewhere, you must do the same for the new parent. And when the panel requirements change, you must remember that you need to perform processing from the parent control.

Everything is potentially randomly a little further down the line.

I would be inclined to put some check of coordinates in the event of leaving the mouse for the panel and only reset the color of the panel if the mouse really went beyond the panel.

Thus, your code for processing the panel remains only on the panel in question.

+1
source

I found a simple solution. I just set the enabled property to false on the label, and that's fine.

+1
source

You can add a MouseEnter event for the label, which also sets the panel color back. You don’t need the MouseLeave event for the label.

Or:

  • Set the MouseEnter event for the panel to set the color of the back panel of the panel.
  • Set the parent Panel control (e.g. Form) of the MouseEnter to reset the color of the back panel.

If you want to make point 2 above without touching the parent control code (as is the case with another user comment), you can do something similar in the Panel ParentChanged event:

  private void panel1_ParentChanged(object sender, EventArgs e) { Panel thisPanel = sender as Panel; if(thisPanel != null && thisPanel.Parent != null) { thisPanel.Parent.MouseEnter += delegate(object senderObj, EventArgs eArgs) { thisPanel.BackColor = SystemColors.Control; }; } } 
0
source

Source: https://habr.com/ru/post/1237799/


All Articles