winfrom 界面上panel控件中的button按钮上下左右键事件

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

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;
}
return true;
}

}

猜你喜欢

转载自www.cnblogs.com/xiazhao/p/9212080.html