问题描述
我正在尝试制作井字游戏程序,想知道我如何确定是否点击了任何按钮以及它是哪个按钮.我目前正在重复每个按钮内的代码:
I am trying to make a tic-tac-toe program, and want to know how I figure out if any of the buttons was clicked and which button it was. I am currently repeating the code inside every button:
private void button1_Click(object sender, EventArgs e)
{
button1.Visible = false;
label1.Text = "X";
Application.DoEvents();
}
private void button2_Click(object sender, EventArgs e)
{
button2.Visible = false;
label2.Text = "X";
Application.DoEvents();
}
private void button3_Click(object sender, EventArgs e)
{
button3.Visible = false;
label3.Text = "X"
Application.DoEvents();
}
有没有更优雅的方法来做到这一点?
Is there a more elegant way to do this?
推荐答案
有两种方法可以完成您的任务(假设使用 WinForms).
There's two ways to accomplish what you're after (assuming WinForms)..
首先,您可以将所有按钮连接起来以指向同一个事件处理程序......并检查其名称:
First, you could wire up all buttons to point to the same event handler.. and check its name:
// In the form designer code:
this.buttonNW.Click += new System.EventHandler(this.button_Click);
this.buttonN.Click += new System.EventHandler(this.button_Click);
this.buttonNE.Click += new System.EventHandler(this.button_Click);
// in the form code:
private void button_Click(object sender, EventArgs e) {
Button thisButton = (Button)sender;
switch (thisButton.Name) {
case "buttonNW":
MessageBox.Show("North West button clicked");
break;
case "buttonN":
MessageBox.Show("Northern button clicked");
break;
case "buttonNE":
MessageBox.Show("North East button clicked");
break;
}
}
其次,您可以将逻辑放入它自己的函数中,并为每个单独的事件处理程序调用该函数:
Secondly, you could just put the logic into it's own function and call that function for each individual event handler:
private void buttonNW_Click(object sender, EventArgs e) {
handleButtonClick("buttonNW");
}
private void buttonN_Click(object sender, EventArgs e) {
handleButtonClick("buttonN");
}
private void buttonNE_Click(object sender, EventArgs e) {
handleButtonClick("buttonNE");
}
private void handleButtonClick(string buttonName) {
switch (buttonName) {
case "buttonNW":
MessageBox.Show("North West button clicked");
break;
case "buttonN":
MessageBox.Show("Northern button clicked");
break;
case "buttonNE":
MessageBox.Show("North East button clicked");
break;
}
}
我个人会选择选项 2,以便一切都清楚.
I would personally go with option 2 so that everything is clear.
不过,这是一个微不足道的练习,因为在井字游戏中您最多只能有 9 个按钮.
It's a trivial exercise though, considering you'll only ever have a maximum of 9 buttons in a tic-tac-toe game.
这篇关于您如何确定是否在 c# 中单击了任何按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!