我有一个小程序,在2D数组中按住4按钮,我想做的是在消息框中显示该数组的'X'和'Y'坐标(单击时)
[我尝试了很多方法,有些方法无效,有些却无法工作,但我无法显示'X'和'Y'值
下图显示了我到目前为止所拥有的:
这是我想出的代码:
namespace _2DArray
{
public partial class Form1 : Form
{
private Button[,] b;
public Form1()
{
InitializeComponent();
b = new Button[2, 2];
b = new Button[,] { {button1,button2 },
{button3, button4}};
}
private void Form1_Load(object sender, EventArgs e)
{
foreach (Button bt in b)
{
bt.Click += new System.EventHandler(this.ClickedButton);
}
}
private void ClickedButton(object sender, EventArgs e)
{
Button s = (Button)sender;
MessageBox.Show("you have clicked button:" + s);
}
}
}
尝试分配某种指针,如按钮的名称以跟踪其坐标
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
b[i, j].Click += new System.EventHandler(this.ClickedButton);
b[i, j].Name =i+" "+j;
}
}
}
private void ClickedButton(object sender, EventArgs e)
{
Button s = (Button)sender;
MessageBox.Show("you have clicked button:" + s.Name);
}
如果我没看错,这是您问题的答案。您正在尝试正确获取按钮的X和Y坐标吗?这是单击按钮的代码:
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show(button1.Location.ToString());
}
使用此代码
private void Form1_Load(object sender, EventArgs e) {
for (int x = 0; x < 2; x++) {
for (int y = 0; x < 2; y++) {
b[x, y].Tag = new Point(x, y);
b[x, y].Click += new System.EventHandler(this.ClickedButton);
}
}
}
private void ClickedButton(object sender, EventArgs e) {
Button s = (Button) sender;
MessageBox.Show("you have clicked button:" + s.Tag.ToString());
}
然后单击button1将显示消息“您已单击按钮:{X = 0,Y = 0}”等
Tag是每个控件具有的属性,其描述是“与该对象关联的用户定义的数据”,因此您可以将其设置为所需的任何对象。
我知道这对操作员来说可能有点晚了,但希望它将对其他人有所帮助。