0

I have a timer event as given below and I have got some suggestions from this post. Could you suggest me what is wrong with this? I am getting the following crash:

Unable to cast object of type System.Windows.Forms.Timer to type System.Windows.Forms.Button. Any suggestions on where I am going wrong??

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();
    }
}
Community
  • 1
  • 1
Neophile
  • 5,660
  • 14
  • 61
  • 107

2 Answers2

2

You have a problem in ButtomTime_Tick method :

   Button CurrentButton = (Button)sender;

sender is not a Button, it's a Timer.

So what you gonna do now ?

You could add a private field in your class

private Button currentButton_;

and

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

and

private void ButtonTimer_Tick(object sender, EventArgs e)
{

            switch (currentButton_.Name)
            {
                case "BoomUp":break;
             }
}
Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
1

In ButtonTimer_Tick the sender is the timer, not a button. Hence you cast a timer into a button (1st line in that method).

JeffRSon
  • 10,404
  • 4
  • 26
  • 51