Witam.
Mam pewnien kłopot z odliczaniem czasu. Chciałem zrobić program stoper. Naciskam start, zaczyna liczyc i wyswietla na bieŻąco czas jaki upływa.
Gdy odliczam w sekundach jest ok. Ale gdy odliczam w milisekundach, sekunda na ekranie jest o kilkanaście milisekund dłuższa od tej z zegarka (z systemu na przykład).
Wykorzystuję Timer'a z toolbox'a w Visual Studio. Gdy Interval jest ustawiony na 1000 wszystko jest ok, ale gdy ustawie na 100 ms to już sie zaczyna sypać. Rozumiem ze pewnie inne rzeczy w tle zajmują ten dodatkowy czas, no ale stoper powinien działać nawet mimo to.
Prawdopodobnie nie znam jakiegoś haczyka. Czy mógłby ktoś podnunąć pomysł?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace licznik
{
public partial class Licznik : Form
{
Stoper nowyStoper;
public Licznik()
{
nowyStoper = new Stoper() { Godzny = 0, Minuty = 0, Sekundy = 0, Mili=0 };
InitializeComponent();
}
private void buttonStart_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void buttonStop_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
nowyStoper.wyswietl(ref labelStoper);
}
private void timer1_Tick(object sender, EventArgs e)
{
nowyStoper.liczCzas();
nowyStoper.wyswietl(ref labelStoper);
}
private void buttonReset_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
nowyStoper.reset();
nowyStoper.wyswietl(ref labelStoper);
}
}
}
<code class="c#">using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace licznik
{
class Stoper
{
private int godziny;
private int minuty;
private int sekundy;
private int mili;
public void liczCzas()
{
mili++;
if(mili>9)
{
sekundy++;
mili = 0;
if (sekundy > 59)
{
minuty++;
sekundy = 0;
if (minuty > 59)
{
godziny++;
minuty = 0;
}
}
}
}
public void wyswietl(ref Label pokaz)
{
pokaz.Text = godziny.ToString("00") + ":" + minuty.ToString("00") + ":" + sekundy.ToString("00") + ":" + mili.ToString("0");
}
public void reset ()
{
godziny = minuty = sekundy = mili = 0;
}
public int Mili { get { return mili; } set { mili = value; } }
public int Sekundy { get { return sekundy; } set { sekundy = value; } }
public int Minuty { get { return minuty; } set { minuty = value; } }
public int Godzny { get { return godziny; } set { godziny = value; } }
}
}