0

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

无法将类型的对象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();
    }
}
4

2 回答 2

2

您的方法有问题ButtomTime_Tick

   Button CurrentButton = (Button)sender;

sender不是a Button,是a 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;
             }
}
于 2013-05-24T09:44:38.957 回答
1

ButtonTimer_Tick发送者中是计时器,而不是按钮。因此,您将计时器转换为按钮(该方法中的第一行)。

于 2013-05-24T09:44:00.127 回答