Home > Mobile >  How do I find button that enabled timer
How do I find button that enabled timer

Time:07-30

I was wondering if it was possible to find which button enabled a timer in C#. Here's my code:

    private void button1_MouseEnter(object sender, EventArgs e) {
        fadeIn_Timer.Start();
    }

    int a;

    private void fadeIn_Timer_Tick(object sender, EventArgs e) {
        var btn = (Button)sender;
        a  = 30;
        if (a >= 255) {a = 255; }
        btn.BackColor = Color.FromArgb(a, 255, 255, 255); // would change back color of button1
        btn.Refresh();
        if (a == 255) { a = 0; fadeIn_Timer.Stop(); }
    }

I already tried var btn = (Button)sender;, but I don't seem to have any luck. If anyone can help me out that would be great!

CodePudding user response:

I suggest you save the Button in the MouseEnter event handler, then you have it for later. Something like this:

private void button1_MouseEnter(object sender, EventArgs e) {
    fadeIn_Timer.Start();
    timerButton = (Button)sender;
}

int a;
Button timerButton;

private void fadeIn_Timer_Tick(object sender, EventArgs e) {
    a  = 30;
    if (a >= 255) {a = 255; }
    timerButton.BackColor = Color.FromArgb(a, 255, 255, 255); // would change back color of button1
    timerButton.Refresh();
    if (a == 255) { a = 0; fadeIn_Timer.Stop(); }
}

That should get you started.

CodePudding user response:

Here's an example for how you could implement this. The confusion is that Timer is a WinForms control but you need the System.Threading.Timer class for this to work.

So create a WinForms solution. Add a Form with a button (button1 in my case) and add the code below in the code behind of the form. When you click the button it should alternate it's background between black and white.

public partial class Form1 : Form
{
    System.Threading.Timer Timer { get; set; }

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Timer = new System.Threading.Timer(button =>
        {
        Button myButton = (Button)button;

        if (myButton.BackColor == Color.Black)
            myButton.BackColor = Color.White;
        else
            myButton.BackColor = Color.Black;

        }, button1, 1000, 1000);
    }
}

CodePudding user response:

You can pass the button object when you initiate the Timer like so:

        Timer = new Timer(someObjectThatWasPassed =>
        {
            // Code here can access 'someObjectThatWasPassed'
        }, someObjectToPass, 1000, 1000);

Make sure that 'Timer' is a field in your class i.e.:

        public class SomeClass
        {
            Timer Timer { get; set; }
  • Related