1. 程式人生 > >二維數組創建按鈕+上下鍵操作

二維數組創建按鈕+上下鍵操作

proc draw 上下 bre cal send ren show control

Button[,] arr;

private void Form1_Load(object sender, EventArgs e)
{
//獲取panel1的寬度計算一行放幾個btn
int panelWidth = panel1.ClientSize.Width;
int num = (panelWidth / (150));//存放數量

//btn坐標
int x = 100;
int y = 50;

var count = 10;
arr = new Button[(count / num) + (count % num != 0 ? 1 : 0), num];
var row = 0;
var col = 0;

for (int i = 0; i <count; i++)
{
var btn = new Button();
btn.Text = "Btn" + i;
btn.Width = 100;
btn.Height = 50;
if (i!=0&&i%num==0)
{
x = 100;
y += 50;
col = 0;
}
else
{
x += 150;
col++;
}

if (i == 0) { x = 100; col = 0; }
row = (i / num);

btn.Tag =row.ToString()+col.ToString();
btn.Location = new System.Drawing.Point(x, y);

arr[row, col] = btn;
panel1.Controls.Add(btn);

}
}


// DLL調用註冊
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Winapi)]
private static extern IntPtr GetFocus();
/// <summary>
/// 當前擁有焦點的控件
/// </summary>
/// <param name="formControl"></param>
/// <returns></returns>
public static Control GetFocusedControl()
{
Control focusedControl = null;
try
{
IntPtr focusedHandle = GetFocus();

if (focusedHandle != IntPtr.Zero)
{
focusedControl = Control.FromChildHandle(focusedHandle);
}
}
catch { }

return focusedControl;
}

protected override bool ProcessDialogKey(Keys keyData)
{
//首先獲取當前焦點的控件
Button btn = (Button)GetFocusedControl();
//獲取當前焦點控件的在數組中對應的位置 此值事先存放在控件的Tag屬性中
int x = int.Parse(btn.Tag.ToString().Substring(0, 1));
int y = int.Parse(btn.Tag.ToString().Substring(1, 1));

switch (keyData)
{
case Keys.Left:
if (y > 0 && arr[x, y - 1] != null)
{
arr[x, y - 1].Focus();
arr[x, y - 1].BackColor = Color.Blue;
btn.BackColor =Color.Transparent;
}
break;
case Keys.Right:
if (y < 2&&arr[x, y + 1] != null)
{
arr[x, y + 1].Focus();
arr[x, y + 1].BackColor = Color.Blue;
btn.BackColor = Color.Transparent;
}
break;
case Keys.Up:
if (x > 0&&arr[x - 1, y] != null)
{
arr[x - 1, y].Focus();
arr[x - 1, y].BackColor = Color.Blue;
btn.BackColor = Color.Transparent;
}
break;
case Keys.Down:
if (x < 3&&arr[x + 1, y] != null)
{
arr[x + 1, y].Focus();
arr[x + 1, y].BackColor = Color.Blue;
btn.BackColor = Color.Transparent;
}
break;
case Keys.Enter:

MessageBox.Show(btn.Text);
break;
}
return true;
}

二維數組創建按鈕+上下鍵操作