views:

140

answers:

1

I'm writing a c# windows app, and as one task, I am creating Panel objects at runtime. I have my custom Panel which is defined as:

class FlowState : Panel
{
:
:
}

I have an init method to set size, location, etc. However once this panel is created on the windows form, I want to handle mouse events, such as mouseDown and mouseUp. If you created a panel at design time and used the gui to define these events, you would get methods like the following (for a panel named 'panel1'):

private void panel1_MouseDown(object sender, MouseEventArgs e)
{
    //do stuff
}

How do I put code into my FlowState object which extends Panel to handle mouse events such as this?

+2  A: 

you can attach the event like this...

private void CreatePanel()
}
    var panel = new FlowState();
    panel.MouseDown += new MouseEventHandler(MouseDown);
}

private void MouseDown(object sender, MouseEventArgs e)
{ 
}
Rohan West
the only comment I would make is that the event is MouseDown and the compiler didn't like the private method also being named MouseDown. I made it onMouseDown and everything was fine.
Brett McCann
In fact, if you had done this at design time, you would see that same line of code (panel.MouseDown +=...) in FlowState.Designer.cs. We can dynamically bind the same methods that the GUI would have done.
cdkMoose