I am developing a piano in C#.
I have the following piece of code in my program:
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
mn1 = new MusicNote();
foreach (MusKey mk in this.panel2.Controls)
{
if (sender == mk)
{
//code
mk.MouseUp += new MouseEventHandler(this.panel1_MouseUp);
}
}
}
What this event does is create a music note and invoke a MouseUp event handler when the user releases the mouse button.
My problem is that if the same music key (MusKey) is pressed a second time, the mk.MouseUp event is executed twice for that single key press. Likewise, if the same key is pressed a fifth time (not necessarily consecutively), the mk.MouseUp event is executed five times for that single key press.
What I want to do is to execute the foreach loop NOT for every MusKey mk, but for every MouseDown event. I do not want the program to “remember” which MusKey mk was pressed.
How can I do this?
You are wiring up the events every time the mouse is pressed. Assign the event handlers once in a different location (like the Load event).
I don’t see any harm in connecting all of your
MouseUpevents for all keys when the application starts up in a manner that guarantees they will only be fired once.If you are doing something more elaborate, you will need to evaluate whether or not the event handler has already been connected to the event in question.