gpt4 book ai didi

c# - 定时器事件 c# Crash

转载 作者:行者123 更新时间:2023-12-03 16:22:39 26 4
gpt4 key购买 nike

我有一个定时器事件,如下所示,我从 this 得到了一些建议邮政。你能告诉我这有什么问题吗?我遇到以下崩溃:

无法转换 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)字段
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;
}
}

关于c# - 定时器事件 c# Crash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16731977/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com