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ではなく、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;
             }
}
于 2013-05-24T09:44:38.957 に答える
1

送信側にButtonTimer_Tickは、ボタンではなくタイマーがあります。したがって、タイマーをボタンにキャストします(そのメソッドの1行目)。

于 2013-05-24T09:44:00.127 に答える