Not returning elapsed time in milliseconds - c#

I've built this simple stopwatch program to measure time in the format of: 00:00:000 [minutes:seconds:milliseconds], but the code ignores the format and counts up like this: 00:00:[seconds here][milliseconds here], so as a result I can only get the elapsed time in 10s of milliseconds and not the individual millisecond.
Here's the display:
The actual time elapsed is 3 seconds and 610 milliseconds.
Code:
namespace stopwatch_1
{
public partial class Form1 : Form
{
int timeMinutes, timeSeconds, timeMSeconds;
bool timerActive;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
resetTime();
}
private void buttonStart_Click(object sender, EventArgs e)
{
timerActive = true;
}
private void buttonStop_Click(object sender, EventArgs e)
{
timerActive = false;
}
private void buttonReset_Click(object sender, EventArgs e)
{
resetTime();
}
private void resetTime()
{
timerActive = false;
timeMinutes = 0;
timeSeconds = 0;
timeMSeconds = 0;
}
private void timerStopwatch_Tick(object sender, EventArgs e)
{
if (timerActive == true)
{
timeMSeconds++;
if (timeMSeconds >= 1000)
{
timeMSeconds = 0;
timeSeconds++;
if (timeSeconds >= 60)
{
timeSeconds = 0;
timeMinutes++;
}
}
}
timerDraw();
}
private void timerDraw()
{
labelMinutes.Text = String.Format("{0:00}", timeMinutes);
labelSeconds.Text = String.Format("{0:00}", timeSeconds);
labelMSeconds.Text = String.Format("{0:000}", timeMSeconds);
}
}
}`
The timer interval is set to one, and I've double checked that all variables are pointing to the right labels so I think the problem lies with where I've formatted the string to display, but I'm not sure where I've gone wrong:
private void timerDraw()
{
labelMinutes.Text = String.Format("{0:00}", timeMinutes);
labelSeconds.Text = String.Format("{0:00}", timeSeconds);
labelMSeconds.Text = String.Format("{0:000}", timeMSeconds);
}
I don't really know how to use string.format in this context, so this is probably where I've gone wrong, all help would be appreciated

The Windows Forms Timer component is single-threaded, and is limited to an accuracy of 55 milliseconds.
You should use a Stopwatch to get a more accurate resolution:
Stopwatch stopwatch;
public Form1()
{
InitializeComponent();
stopwatch = new Stopwatch();
}
private void Form1_Load(object sender, EventArgs e)
{
// do nothing
}
private void buttonStart_Click(object sender, EventArgs e)
{
stopwatch.Start();
}
private void buttonStop_Click(object sender, EventArgs e)
{
stopwatch.Stop();
}
private void buttonReset_Click(object sender, EventArgs e)
{
stopwatch.Reset();
}
private void timerStopwatch_Tick(object sender, EventArgs e)
{
timerDraw();
}
private void timerDraw()
{
labelMinutes.Text = String.Format("{0:00}", stopwatch.Elapsed.Minutes);
labelSeconds.Text = String.Format("{0:00}", stopwatch.Elapsed.Seconds);
labelMSeconds.Text = String.Format("{0:000}", stopwatch.Elapsed.Milliseconds);
}
EDIT:
You should also reduce the Interval on your timer, since there is no need to refresh the labels on a 1ms interval anymore.

Related

How to make a label change its text every some time in C# windows forms

I have a label that I want to update every 5 seconds. It should change from 1921 to 1922 onward till 1992. I have tried using a timer but it gave me an error about being accessed on the wrong thread. The code I used was:
public partial class Form1 : Form
{
int x = 1921;
public Form1()
{
InitializeComponent();
}
System.Timers.Timer myTimer = new System.Timers.Timer(1000);
private void UpdateLabel(object sender, ElapsedEventArgs e)
{
label1.Text = x.ToString();
x += 1;
}
private void Form1_Load(object sender, EventArgs e)
{
myTimer.Elapsed += UpdateLabel;
myTimer.Start();
}
}
Try this:
private void UpdateLabel(object sender, ElapsedEventArgs e)
{
//Invoke makes the UI thread call the delegate.
Invoke((MethodInvoker)delegate {label1.Text = x.ToString(); });
x += 1;
}
try this
private readonly object y = new object();
int x = 1921;
public Form1()
{
InitializeComponent();
}
System.Timers.Timer myTimer = new System.Timers.Timer(1000);
private void UpdateLabel(object sender, ElapsedEventArgs e)
{
Invoke((MethodInvoker)(() => { lock (y) { label1.Text = x.ToString(); x++; } }));
}
private void Form1_Load(object sender, EventArgs e)
{
myTimer.Elapsed += UpdateLabel;
myTimer.Start();
}

How could I check if progress bar is full and then open an .bat file?

I don't know exactly where the code should be put and what code should look like. I need help, because I am very new to c#
{
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
this.timer1.Start();
}
private void Timer1_Tick(object sender, EventArgs e)
{
this.progressBar1.Increment(1);
}
private void Form1_Load(object sender, EventArgs e)
{
this.TopMost = true;
}
private void ProgressBar1_Click(object sender, EventArgs e)
{
}
}
}
When I try the method from old videos, there is no such a thing as it and it shows that progressBar1 doesn't exist.
private void Timer1_Tick(object sender, EventArgs e)
{
this.progressBar1.Increment(1);
If (progressBar1.Value >= progressBar1.Maximum)
{
// do something
}
}
Just compare the progressBar1.Value
// progressBar1.Value = 0;
// progressBar1.Minimum = 0;
// progressBar1.Maximum = 100;
private void Timer1_Tick(object sender, EventArgs e)
{
this.progressBar1.Increment(1);
if(progressBar1.Value == progressBar1.Maximum){
Process.Start("c:\\file.bat");
}
}

Spambot repeat part won't spam fast

I'm working on a spambot but there is 1 problem I can't solve. I made buttons you can press, it says how much you want to spam. If you want to spam you will get a certain amount of time to go to the place where you want to spam. I made a function for how much the text will spam. But the problem is when it send 1 message it wait the certain amount of time time and not the 500 miliseconds
The script is written in C#. The target framework is: .NET Framework 4.6.1.
public partial class Form1 : Form
{
public void Time()
{
for (int i = 0; i <= 10;)
{
Stuur();
i++;
}
} // 10x
public void Stuur() // does the sending
{
System.Threading.Thread.Sleep(500);
SendKeys.Send(textBox3.Text);
SendKeys.Send("{ENTER}");
}
public Form1()
{
InitializeComponent();
}
private void textBox4_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Rush B", "5 sec voor spam",
MessageBoxButtons.OK, MessageBoxIcon.Error);
System.Threading.Thread.Sleep(5000);
Time();
}
private void button2_Click(object sender, EventArgs e) // the credit
block
{
if (textBox6.Visible == true)
{
textBox6.Visible = false;
} else {
textBox6.Visible = true;
}
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
}
}
Maybe something along these lines?
public void Stuur() // does the sending
{
System.Threading.Thread.Sleep(5000);
SendKeys.Send(textBox3.Text);
SendKeys.Send("{ENTER}");
}
public Form1()
{
InitializeComponent();
}
private void textBox4_TextChanged(object sender, EventArgs e) { }
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i <= Int32.Parse(textBox.Text4); i++) {
Stuur();
}
}
private void button2_Click(object sender, EventArgs e) // the credit block
{
if (textBox6.Visible == true)
{
textBox6.Visible = false;
}
else
{
textBox6.Visible = true;
}
}
private void checkBox1_CheckedChanged(object sender, EventArgs e) { }
}
edit: closed parenthesis

WPF Audio Player using MediaElement sometimes lags

this is the source code for the audio player:
public partial class MainWindow : Window
{
private DispatcherTimer timer;
public MainWindow()
{
InitializeComponent();
mPlayer.LoadedBehavior = MediaState.Manual;
mPlayer.UnloadedBehavior = MediaState.Manual;
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(500);
timer.Tick += timer_Tick;
mPlayer.MediaOpened += mPlayer_MediaOpened;
}
void mPlayer_MediaOpened(object sender, RoutedEventArgs e)
{
TimeSpan ts = mPlayer.NaturalDuration.TimeSpan;
SeekSlider.Maximum = ts.TotalSeconds;
}
void timer_Tick(object sender, EventArgs e)
{
SeekSlider.Value = mPlayer.Position.TotalSeconds;
}
private MediaElement mPlayer = new MediaElement();
private void ButtonOpen_Click(object sender, RoutedEventArgs e)
{
try
{
var ofd = new OpenFileDialog();
if (ofd.ShowDialog() == true)
{
timer.Start();
mPlayer.Source = new Uri(ofd.FileName);
mPlayer.Volume = VolumeSlider.Value;
timer.Start();
mPlayer.Play();
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
private void ButtonPlay_Click(object sender, RoutedEventArgs e)
{
mPlayer.Play();
timer.Start();
}
private void ButtonPause_Click(object sender, RoutedEventArgs e)
{
mPlayer.Pause();
timer.Stop();
}
private void ButtonStop_OnClick(object sender, RoutedEventArgs e)
{
timer.Stop();
mPlayer.Stop();
}
private void SeekSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
mPlayer.Position = TimeSpan.FromSeconds(SeekSlider.Value);
}
private void VolumeSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
mPlayer.Volume = VolumeSlider.Value;
}
}
I don't know why it has sudden lags. Please help me in finding the problem.
If you think that MediaElement is not appropriate for playing different kinds of audio files. Please suggest an alternative.
The SeekSlider_ValueChanged event was firing too often. so that was causing some lag.
So i solved the problem using the Thumb.DragCompleted event. After this the playback is pretty smooth.

How to let user enter an integer and start timer based off on that value

I am in the process of creating my first c# project, a personal time tracking application. Pretty basic so far however before I get any further I would like to have the timer working properly.
So far the timer will start / stop and reset. However a curious thing that I wanted to be able to do was for the user to set a time and have the counter start from there.
So if they wanted to start at 20 minutes and have it count up, then it would
example: 00:20:00 would count from 20 and add to it.
However so far I have not figured it out.
Here is the code:
namespace TimeTracker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
TimerBox.Text = string.Format("00:00:00");
}
int ss = 0;
public void StartButton_click(object sender, EventArgs e)
{
timer1.Start();
timer1.Enabled = true;
timer1.Interval = 1000;
}
public void StopButton_click(object sender, EventArgs e)
{
timer1.Stop();
TimerBox.Text = TimeSpan.FromSeconds(ss).ToString();
}
public void ResetButton_click(object sender, EventArgs e)
{
ss = 0;
TimerBox.Text = TimeSpan.FromSeconds(ss).ToString();
}
private void timer1_Tick(object sender, EventArgs e)
{
ss++;
TimerBox.Text = TimeSpan.FromSeconds(ss).ToString();
}
}
}
Here is the application:
http://imgur.com/VNXVrtp
Any help would be appreciated, I can provide more details if you would like!
EDIT: Since it was unclear, my question is:
What process would be better for coding this, adding to the integer or if there is a better way of implementing this?
You can set the initial value of that ss variable to any predefined integer entered by user, e.g.
DateTime _dt = DateTime.Parse(TimertBox.Text);
int ss = _dt.Second + _dt.Minute * 60 + _dt.Hour * 3600;
Try something like...
public partial class Form1 : Form
{
private TimeSpan Offset = new TimeSpan();
private System.Diagnostics.Stopwatch SW = new System.Diagnostics.Stopwatch();
public Form1()
{
InitializeComponent();
timer1.Interval = 1000;
UpdateTime();
}
public void StartButton_click(object sender, EventArgs e)
{
TimeSpan TS;
if (TimeSpan.TryParse(TimerBox.Text, out TS))
{
Offset = TS;
}
else
{
MessageBox.Show("Invalid Starting Time. Resetting to Zero");
Offset = new TimeSpan();
}
SW.Restart();
UpdateTime();
timer1.Start();
}
public void StopButton_click(object sender, EventArgs e)
{
SW.Stop();
timer1.Stop();
}
public void ResetButton_click(object sender, EventArgs e)
{
Offset = new TimeSpan();
if (SW.IsRunning)
{
SW.Restart();
}
else
{
SW.Reset();
}
UpdateTime();
}
private void timer1_Tick(object sender, EventArgs e)
{
UpdateTime();
}
private void UpdateTime()
{
TimerBox.Text = Offset.Add(SW.Elapsed).ToString(#"hh\:mm\:ss");
}
}
Try using the timer normally (from 00:00:00.00), and when updating your output label / textbox / etc. just add the time the user has written.

Categories

Resources