@jundullah 007 , Welcome to Microsoft Q&A, I recommend that you use the control tableLayoutPanel to store the box or square.
Also, I suggest that you use the Arrrow key to control the selection.
Here is a code example you could refer to.
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < tableLayoutPanel1.RowCount; i++)
{
for (int j = 0; j < tableLayoutPanel1.ColumnCount; j++)
{
Button button1 = new Button() { BackColor = Color.Red, AutoSize = true };
button1.GotFocus += Button_GotFocus;
button1.LostFocus += Button_LostFocus;
button1.PreviewKeyDown += Button_PreviewKeyDown;
tableLayoutPanel1.Controls.Add(button1, i, j);
}
}
Button btn = tableLayoutPanel1.Controls.Cast<Button>().FirstOrDefault();
btn.BackColor = Color.Black;
}
private void Button_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
var btn = sender as Control;
var pos = tableLayoutPanel1.GetPositionFromControl(btn);
bool moveFocus = false;
switch (e.KeyCode)
{
case Keys.Up:
pos.Row = (pos.Row > 0) ? pos.Row - 1 : tableLayoutPanel1.RowCount - 1;
moveFocus = true;
break;
case Keys.Down:
pos.Row = (pos.Row < (tableLayoutPanel1.RowCount - 1)) ? pos.Row + 1 : 0;
moveFocus = true;
break;
case Keys.Left:
pos.Column = (pos.Column > 0) ? pos.Column - 1 : tableLayoutPanel1.ColumnCount - 1;
moveFocus = true;
break;
case Keys.Right:
pos.Column = (pos.Column < (tableLayoutPanel1.ColumnCount - 1)) ? pos.Column + 1 : 0;
moveFocus = true;
break;
}
if (moveFocus)
{
e.IsInputKey = true;
var ctrl = tableLayoutPanel1.GetControlFromPosition(pos.Column, pos.Row);
if (ctrl != null) this.ActiveControl = ctrl;
}
}
private void Button_LostFocus(object sender, EventArgs e)
{
Button button = (Button)sender;
button.BackColor = Color.Red;
}
private void Button_GotFocus(object sender, EventArgs e)
{
Button button=(Button)sender;
button.BackColor = Color.Black;
}
Tested result:
If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.