[英]2D Array Buttons Display X and Y
我有一個小程序,在 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);
}
}
}
如果我沒看錯,這里是你問題的答案。 您想正確獲取按鈕的 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 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);
}
使用此代碼
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 是每個控件都有的一個屬性,它的描述是“與對象關聯的用戶定義數據”,因此您可以將其設置為您喜歡的任何對象。
我知道這對操作來說可能有點晚了,但希望它會幫助其他人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.