定时器事件c#崩溃
本文关键字:崩溃 事件 定时器 | 更新日期: 2023-09-27 18:15:04
我有一个定时器事件如下所示,我从这篇文章中得到了一些建议。你能告诉我这有什么问题吗?我得到以下崩溃:
无法将类型System.Windows.Forms.Timer
的对象强制转换为类型System.Windows.Forms.Button
。有什么建议在哪里我错了??
public MainForm()
{
InitializeComponent();
ButtonTimer.Tick += new EventHandler(ButtonTimer_Tick);
ButtonTimer.Interval = 100;
}
private void ButtonTimer_Tick(object sender, EventArgs e)
{
Button CurrentButton = (Button)sender;
string PressedButton = CurrentButton.Name;
switch (PressedButton)
{
case "BoomUp":break;
}
}
private void BoomUp_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
//ButtonTimer.Enabled = true;
ButtonTimer.Start();
}
}
private void BoomUp_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ButtonTimer.Stop();
}
}
ButtomTime_Tick
方法有问题:
Button CurrentButton = (Button)sender;
sender
不是Button
,它是Timer
。
那么你现在要做什么呢?
你可以在你的类中添加一个私有字段
private Button currentButton_;
和
private void BoomUp_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
currentButton_ = e.Button;//but I don't know if e.Button has a Name "BoomUp"
//you can set the name manually if needed :
currentButton_.Name = "BoomUp";
//ButtonTimer.Enabled = true;
ButtonTimer.Start();
}
}
和
private void ButtonTimer_Tick(object sender, EventArgs e)
{
switch (currentButton_.Name)
{
case "BoomUp":break;
}
}
在ButtonTimer_Tick
中,发送者是计时器,而不是按钮。因此,您将计时器强制转换为按钮(该方法的第一行)。