【问题标题】:Timer event c# Crash定时器事件 c# Crash
【发布时间】:2013-05-24 09:42:03
【问题描述】:

我有一个计时器事件,如下所示,我从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();
    }
}

【问题讨论】:

    标签: c# winforms timer crash


    【解决方案1】:

    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;
                 }
    }
    

    【讨论】:

    • 是的,这正是崩溃发生的地方,但我如何获得当前按钮? (如果不是来自发件人)
    • 好的,知道了。在尝试获取名称时稍微更改了它,但得到了它的要点。谢谢。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-24
      • 1970-01-01
      • 2020-09-14
      • 2017-10-10
      相关资源
      最近更新 更多