我从之前的问题得到了答案,但它并不是很正确。我希望button1
与button2
做同样的事情,但事实并非如此。我也想知道如何在代码中添加更多按钮(我总共需要4个按钮)。我不知道是否有更简单的方法可以达到与我想要做的相同的结果。如果有,请向我解释。我一直在努力使用c#(或者我认为他们称之为Windows我不太确定),因为我相对较新。我正在努力学习如何修复我的代码但是,这个答案并不是我所熟悉的。我通常会将Button btn = (Button)sender;
与tmr.Tick += new EventHandler(timer_Tick);
一起使用。这是我得到的答案(我编辑了一下,这可能是我出错的地方)。
public Form1()
{
InitializeComponent();
this.SerCorrespondingButtons();
this.SetCorrespondingInitialButtonInscriptions();
}
System.Windows.Forms.Timer tmr = new System.Windows.Forms.Timer();
private Dictionary<Button, Label> correspondingControls;
private Dictionary<Button, string> initialButtonInscriptions;
private List<string> sayingsList;
private Button currentButton;
private int i;
private void SerCorrespondingButtons()
{
correspondingControls = new Dictionary<Button, Label>()
{
{this.button1, this.label1},
{this.button2, this.label2},
};
}
private void SetCorrespondingInitialButtonInscriptions()
{
this.initialButtonInscriptions = new Dictionary<Button, string>()
{
{this.button1, this.button1.Text},
{this.button2, this.button2.Text}
};
}
private void button2_Click(object sender, EventArgs e)
{
var button = sender as Button;
if (this.currentButton != null)
{
this.currentButton.Enabled = true;
this.currentButton.Text = this.initialButtonInscriptions[this.currentButton];
this.currentButton.Click += this.button2_Click;
tmr.Enabled = false;
tmr.Tick -= timer2_Tick;
}
this.currentButton = button;
var saying = this.correspondingControls[button];
saying.Visible = true;
button.Text = "Click To Hide Saying";
button.Click -= button2_Click;
button.Click += button2_Click2;
}
private void button2_Click2(object sender, EventArgs e)
{
var button = sender as Button;
var saying = this.correspondingControls[button];
saying.Visible = true;
if (saying.Visible)
{
button.Enabled = false;
saying.Visible = false;
button.Text = "Reactivating in 5 seconds";
tmr.Interval = 1000;
button.Click -= button2_Click2;
button.Click += button2_Click;
this.i = 4;
tmr.Tick += timer2_Tick;
tmr.Enabled = true;
}
}
private void timer2_Tick(object sender, EventArgs e)
{
if (i != 0)
{
this.currentButton.Text = "Reactivating in " + i + " seconds";
i -= 1;
}
}
它没有附带说明,所以,如果你可以在你的答案中添加备注/评论,我将非常感激。如果你也可以给我链接,我应该看看,我真的很感激!正如我所说,我尝试了其他方法但是,他们还没有接近这种方式。先谢谢你了!
答案 0 :(得分:0)
Button_click
是一个事件,在c#事件中,用于通知对象任何修改或特定对象发生的事情。
按钮是一个对象,它有很多与Click点击相同的事件
因此,如果您希望按钮执行相同的事件,您可以只听取它们全部并为它们制作一个FUNCTION/OPERATION
你可以参考这个链接
C# How to use one click event handler for multiple buttons