Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Minutes to Milliseconds

The Timer class in Winforms has a property called, Interval and it

Gets or sets the time, in milliseconds, before the Tick event is raised relative to the last occurrence of the Tick event.

On my form I have a text box where the user can input in minutes how long they want to set the timer for.

However I am unable to use the function I made to convert minutes to milliseconds:

public static double ConvertMinutesToMilliseconds(double minutes)
{
  return TimeSpan.FromMinutes(minutes).TotalMilliseconds;
}

My code looks like this:

if (result1 == DialogResult.Yes)
{
    Timer tm;
    tm = new Timer();

    tm.Interval = int.Parse(textBox2.Text);
    tm.Interval = ConvertMinutesToMilliseconds(tm.Interval);
    tm.Tick += new EventHandler(button1_Click);

    string pastebuffer = DateTime.Now.ToString();
    pastebuffer = "### Edited on " + pastebuffer + " by " + txtUsername.Text + " ###";
    Clipboard.SetText(pastebuffer);

    tm.Start();
}

My error is: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)

like image 225
PriceCheaperton Avatar asked Dec 08 '22 21:12

PriceCheaperton


1 Answers

System.Windows.Forms.Timer.Interval is of type int - it's slightly confusing because System.Timers.Timer.Interval is of type double. So you're trying to assign the result of your method (a double) to a property of type int. That isn't going to work. You can just cast, of course:

timer.Interval = (int) ConvertMinutesToMilliseconds(...);

However, I'd take this opportunity to refactor your code a bit too. Initially you're assigning the minutes value to timer.Interval, which is simply wrong in terms of units. You're just using it as a temporary variable, effectively - so make that clearer, and try to use "assign at point of declaration" for clarity too:

if (result1 == DialogResult.Yes)
{
    // TODO: Use int.TryParse to handle invalid input
    int minutes = int.Parse(textBox2.Text);
    Timer timer = new Timer
    {
        // I don't actually think it's worth having a method for this...
        Interval = (int) TimeSpan.FromMinutes(minutes).TotalMilliseconds
    }
    // Use method group conversion instead of new EventHandler(...)
    // TODO: Rename button1_Click to a name which says what it actually does
    timer.Tick += button1_Click;

    // Interpolated strings make life simpler
    Clipboard.SetText($"### Edited on {DateTime.Now} by {txtUsername.Text} ###");

    timer.Start();
}

Then you just need to worry (if I remember correctly) about keeping a reference to the timer instance so it doesn't get garbage collected. So you may want some sort of "list of active timers". It's possible that I've misremembered this, but you may well want to keep that list anyway, so that you can stop all the active timers at an appropriate time.

like image 84
Jon Skeet Avatar answered Dec 29 '22 06:12

Jon Skeet