Home > other >  C# - Getting to know if any winform button (of 64 buttons) was pressed
C# - Getting to know if any winform button (of 64 buttons) was pressed

Time:06-14

I am building a checkers game using Windows Forms on C#. The board size is 8X8 and I have 64 button - 32 of them are active, 32 of them are inactive. enter image description here

I am holding an array of 64 "UpgradedButtons" - Winform buttons that hold [x,y] as their position in the buttons array.

private UpgradedButton[,] m_GameButtons;

for (int i = 0; i < m_GameSize; i  )
            {
                for (int j = 0; j < m_GameSize; j  )
                {
                    m_GameButtons[i, j] = new UpgradedButton(new Point(i,j));
                    m_GameButtons[i, j].Location = new Point(left, top);
                    m_GameButtons[i, j].Size = m_ButtonSize;
                    left  = m_ButtonSize.Width;
                    if ((i % 2 == 0 && j % 2 == 0) || (i % 2 != 0 && j % 2 != 0))
                    {
                        m_GameButtons[i, j].Enabled = false;
                    }

                    if ((i < (m_GameSize / 2) - 1) && ((i % 2 == 0 && j % 2 != 0) || (i % 2 != 0 && j % 2 == 0)))
                    {
                        m_GameButtons[i, j].Text = "O";
                    }

                    else if (i > (m_GameSize / 2) && ((i % 2 == 0 && j % 2 != 0) || (i % 2 != 0 && j % 2 == 0)))
                    {
                        m_GameButtons[i, j].Text = "X";
                    }
                    Controls.Add(m_GameButtons[i, j]);
                }
            }

The problem that I encounter is that when a key is pressed, I have no idea which one is the one.
I can scan the array I hold with a for loop, and ask each button "Have YOU been pressed? If yes, do something.".
But I feel that there is more efficient way than asking all buttons, all time, if they have been pressed.
What am I missing here?
Thanks!

CodePudding user response:

You can give each button an individualized event handler:

var _i = i;
var _j = j;
m_GameButtons[i, j].Click  = (sender, e) => MyButtonClicked(_i, _j);

...

void MyButtonClicked(int i, int j) 
{
    // here, we have the indexes...
}

Note: Those _i, _j copies are necessary, because, otherwise, the loop variables i, j would be captured by the lambda, and you would always get the "final" value of those variables, independent of the actual button that has been clicked.

CodePudding user response:

The event that is executed as a result of clicking a button will receive a reference the to that button in its "sender" argument.

You can the argument to UpgradedButton and then access the X,y values you stored there.

  • Related