Reputation: 18290
I have an User Control that host another controls like panel, chart controls.
Right now i have implemented the Header Panel control's MouseClick event to capture the mouse event, but i need to capture mouse click or mouseDown event on the whole user control area.
pnlHeader.MouseUp += new MouseEventHandler(pnlHeader_MouseUp); //it is working
//Not able to capture because child control coverup all area of the usercontrol.
this.MouseDown += new MouseEventHandler(MyCustomControl_MouseDown);
I went through this SO thread, but it does not help me regarding mouse click or mouse down event.
So what is correct and efficient way to capture user control mouse event??
Any idea or suggestion with some reference code(if possible) will be accepted.
Thanks in advance.
Upvotes: 3
Views: 5037
Reputation: 6026
There is a way to write this without so much code. You could create your own MouseDown
event handler in your user control that hides the existing handler and within directly hooks each control on your UserControl. For example, here's the MouseDown handler for a UserControl that contains a Panel
and a ListBox
:
// MouseDown event handler within UserControl
public new event MouseEventHandler MouseDown
{
add
{
panel1.MouseDown += value;
listBox1.MouseDown += value;
}
remove
{
panel1.MouseDown -= value;
listBox1.MouseDown -= value;
}
}
If you had more controls on your UserControl, you just add them to each section.
Your call in your parent WinForm must hook the MouseDown
event for your UserControl like this:
myUserControl1.MouseDown += myUserControl1_MouseDown;
Upvotes: 1
Reputation: 4856
namespace WindowsFormsApplication1
{
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
this.OnUCMouseUp += new MouseEventHandler(UserControl1_OnUCMouseUp);
panel1.MouseUp += new MouseEventHandler(panel1_MouseUp);
}
void UserControl1_OnUCMouseUp(object sender, MouseEventArgs e)
{
MessageBox.Show("From userControl");
}
void panel1_MouseUp(object sender, MouseEventArgs e)
{
InvokeMouseUp(this, e);
}
public event MouseEventHandler OnUCMouseUp;
protected void InvokeMouseUp(object sender, MouseEventArgs e)
{
if (this.OnUCMouseUp != null)
this.OnUCMouseUp(sender, e);
}
}
}
Upvotes: 0
Reputation: 50672
There is no way of bubbling events in WinForms like there is in HTML or in WPF
How do I grab events from sub-controls on a user-control in a WinForms App?
So you will always need to add extra code.
Upvotes: 4