-1

Currently in the process of creating a simple (what I thought was simple) visual piano project that can be operated by both clicking the buttons on screen and using the keyboard.

I would like to have a visual signal on the screen that shows what note I played based on what key I pressed on the keyboard. I'd like to do this by changing the backcolor property. I am trying to avoid having to copy and paste

 btnC.BackColor = Color.White;
 btnD.BackColor = Color.White;
 btnE.BackColor = Color.White;

etc. in to every keydown function.

Any tips or suggestions are greatly appreciated. Thank you in advance.

BailesMc
  • 11
  • 2
  • Wouldn't you only have to change the color of the one being pressed? Why would you have to change the color of every screen element in every event handler? – David Jan 12 '16 at 17:36

2 Answers2

0

Why not group them into an array and iterate over them?

var buttons = new Button[] { btnC, btnD, btnE ,... };
foreach(var button in buttons)
   button.BackColor = Color.White;

Alternativley use your Form object to query for all children controls and check if it is an instance of Button. (Only works if you have them isolated in an container or no other buttons in the GUI)

Maximilian Gerhardt
  • 5,188
  • 3
  • 28
  • 61
0

A little more info would probably help, but my first thought was to write your own generic event handler that can be used for every button, and then attach it to whichever event is most useful, probably the Click event.

private void fooEvent (object sender, EventArgs e)
{
    // You can cast the sender as Textbox 
    // and do whatever you need to with it

    if (((Textbox)sender).BackColor == Color.Black)
        ((Textbox)sender).BackColor = Color.White;
    else
        ((Textbox)sender).BackColor = Color.Black;
}

Attach like so:

textboxfoo.Click += new System.EventHandler(fooEvent);