I\'m new in programming.
I don\'t know how to explain well!!.
How can i make my WinForms application understand the button location, for example imagine a nu
I'm assuming you are talking about buttons within a Form.
Put them in a List like that
List<Button> buttons = new List<Button>() {Button1, Button2...}
Now you know what button you are on and going up means you need to take the current index and substract 3* from it (Button6 -> Button3) and just use that as the new index for the list. For down you add 3* and left/right are minus/plus 1.
Now you just have to define your edge cases: What if you press down or right when you are on Button9?
*This value changes based on the amount of columns. 3 columns => +/-3; 4 col => +/-4
You can add your Buttons to a TableLayoutPanel, so each Button's position is determined by the TableLayoutPanel's (Column:Row) coordinates.
tlpButtons) with enough Rows and Columns to contain your Buttons. You can add/remove Rows and Column at run-time, if needed.buttons_PreviewKeyDown).Key.Up or Keys.Down are pressed, the PreviewKeyDown handler of the Buttons is invoked. The sender argument references the control that triggered the event, so we cast sender to Control (since only a Control type reference is needed, we don't use any property specific to a derived type, like Button)± 1, depending on what cursor Key has been pressed (while checking whether the new value is in the [0 : RowsCount] range).This is the result:
Note:
the buttons_PreviewKeyDown event handler is the same for all Buttons/Controls.
tlpButtons is the name of the TableLayoutControl used as container for the Buttons/Controls
Updated to also work with a Numeric Pad when either active or inactive.
private void buttons_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
var btn = sender as Control;
var pos = tlpButtons.GetPositionFromControl(btn);
bool moveFocus = false;
switch (e.KeyCode) {
case Keys.NumPad8:
case Keys.Up:
pos.Row = (pos.Row > 0) ? pos.Row - 1 : tlpButtons.RowCount - 1;
moveFocus = true;
break;
case Keys.NumPad2:
case Keys.Down:
pos.Row = (pos.Row < (tlpButtons.RowCount - 1)) ? pos.Row + 1 : 0;
moveFocus = true;
break;
case Keys.NumPad4:
if (pos.Column > 0) {
pos.Column -= 1;
}
else {
pos.Column = tlpButtons.ColumnCount - 1;
pos.Row = pos.Row > 0 ? pos.Row - 1 : tlpButtons.RowCount - 1;
}
moveFocus = true;
break;
case Keys.NumPad6:
if (pos.Column < (tlpButtons.ColumnCount - 1)) {
pos.Column += 1;
}
else {
pos.Column = 0;
pos.Row = (pos.Row < tlpButtons.RowCount - 1) ? pos.Row + 1 : 0;
}
moveFocus = true;
break;
}
if (moveFocus) {
e.IsInputKey = true;
var ctrl = tlpButtons.GetControlFromPosition(pos.Column, pos.Row);
if (ctrl != null) this.ActiveControl = ctrl;
}
}