Stop a Timer when it reaches zero - c#

How do I stop my timer when it reaches zero?
I have this windows form code here:
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;
using System.Timers;
namespace SoftwareEngineering
{
public partial class MainGame : Form
{
int minutes = 2;
int seconds = 0;
private TimeSpan countdowntime;
public MainGame()
{
InitializeComponent();
StartPosition = FormStartPosition.CenterScreen;
}
private void NewGame_Click(object sender, EventArgs e)
{
setcountdown(minutes, seconds);
timer1.Enabled = true;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
TimeSpan tSecond = new TimeSpan(0, 0, 1);
countdowntime = countdowntime.Subtract(tSecond);
if(seconds > 0)
{
timeremaining.Text = countdowntime.Minutes.ToString() + ":" + countdowntime.Seconds.ToString();
}
else
{
timeremaining.Text = "Times Up!";
timer1.Stop();
}
}
private void setcountdown(int min,int sec)
{
TimeSpan temp = new TimeSpan(0 , min , sec);
countdowntime = temp;
}
The code works but once it reaches "0:0" , it will continue to decrement to "0:-1" and so on, my condition doesn't seem to work when stopping the timer.
This is my condition from the above:
if(seconds > 0)
{
timeremaining.Text = countdowntime.Minutes.ToString() + ":" + countdowntime.Seconds.ToString();
}
else
{
timeremaining.Text = "Times Up!";
timer1.Stop();
}

Following my comments. You could change your timer code to this. It will start with displaying your initial value
private void timer1_Tick(object sender, EventArgs e)
{
//I've edited you're code if(countdowntime.TotalSeconds > 0)
//to this because # "0:1" It will display Times Up
if (countdowntime.TotalSeconds >= 0)
{
timeremaining.Text = countdowntime.Minutes.ToString() + ":" + countdowntime.Seconds.ToString();
}
else
{
timeremaining.Text = "Times Up!\r\n";
timer1.Stop();
return;
}
TimeSpan tSecond = new TimeSpan(0, 0, 1);
countdowntime = countdowntime.Subtract(tSecond);
}

I am not sure this will work, but I think it would:
private void timer1_Tick_1(object sender, EventArgs e)
{
counter--; [COLOR=#006400]//Decrease the counter, just like the timer decreases.[/COLOR]
if (counter == 0) [COLOR=#006400]//If we hit 0, or any other number we'd like to check.[/COLOR]
{
MessageBox.Show("Time Up!");
counter = timer.Interval;[COLOR=#006400]//Reset the counter.[/COLOR]
timer.Start();[COLOR=#006400]//Re-start the timer.[/COLOR]
}
}
DEMO Page
Stop Number

Related

How to change label text and color when a condition is met? (C#)

I am making a password generator and on websites when you enter certain conditions are met the strength of the password changes how can I change the color and text of the label when the password strength is >= 8, <8<10, >12?
Here is the Code:
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 Password_Generator
{
public partial class PassGen : Form
{
int currentPasswordLength = 0;
Random Character = new Random();
private void PasswordGenerator(int PasswordLength)
{
String validChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$&?";
String randomPassword = "";
//25
for(int i = 0; i < PasswordLength; i++)
{
int randomNum = Character.Next(0, validChars.Length);
randomPassword += validChars[randomNum];
}
Password.Text = randomPassword;
}
public PassGen()
{
InitializeComponent();
PasswordLengthSlider.Minimum = 5;
PasswordLengthSlider.Maximum = 22;
PasswordGenerator(5);
}
private void Label1_Click(object sender, EventArgs e)
{
}
private void Copy_Click(object sender, EventArgs e)
{
Clipboard.SetText(Password.Text);
}
//52
private void PasswordLength_Click(object sender, EventArgs e)
{
}
private void PasswordLengthSlider_Scroll(object sender, EventArgs e)
{
PasswordLength.Text = "Password Length:" + " " + PasswordLengthSlider.Value.ToString();
currentPasswordLength = PasswordLengthSlider.Value;
PasswordGenerator(currentPasswordLength);
}
private void pswdStrengthTest()
{
if (currentPasswordLength <= 8)
{
pswdStrength.Text = "weak";
pswdStrength.ForeColor = Color.Red;
} else if (currentPasswordLength<= 9)
{
pswdStrength.Text = "ok";
pswdStrength.ForeColor = Color.Blue;
}
}
//78
private void pswdStrength_Click(object sender, EventArgs e)
{
}
}
}
If anyone could help me with this it would be greatly appreciated. This is based off a tutorial I found on YouTube. I'm not sure what the video is called but if it helps I could search for it and update my posting.
Try this:
Password.TextChanged += (s1, e1) =>
{
if (Password.Text.Length > 10)
pswdStrength.ForeColor = Color.Green
else if (Password.Text.Length > 8)
pswdStrength.ForeColor = Color.Blue
else
pswdStrength.ForeColor = Color.Red
};
Your code looks like a windows form application.
If you have for example one objetc txt_password, check to code some of these events:
TextChanged: this occurs when your textbox has been changed
Others events could be:
KeyPress or KeyDown

Application is not responding

What the application should do
This application should take the input of time (seconds, minutes and hours) and shutdown the computer after that time. It should also update the text box with how long left until the computer has shut down.
What the application actually does
I had an issue that I 'fixed' where the called ac across threads weren't safe, so I fixed it and I don't get that error now. However, the updateThread doesn't update and print the time left; and the text box doesn't get "test" appended to it. The UI also becomes Not Responding. Any help would be much appreciated.
Also, if you see anything else that could be done better, please comment and explain. Thanks!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ShutdownPC
{
public partial class Form1 : Form
{
int inputHours;
int inputMinutes;
int inputSeconds;
Thread sleepingThread;
Thread updatingThread;
NotifyIcon shutdownPCIcon;
Icon defaultIcon;
public Form1()
{
InitializeComponent();
defaultIcon = new Icon("defaultIcon.ico");
shutdownPCIcon = new NotifyIcon();
shutdownPCIcon.Icon = defaultIcon;
shutdownPCIcon.Visible = true;
MenuItem progNameMenuItem = new MenuItem("ShutdownPC by Conor");
MenuItem breakMenuItem = new MenuItem("-");
MenuItem quitMenuItem = new MenuItem("Quit");
ContextMenu contextMenu = new ContextMenu();
contextMenu.MenuItems.Add(progNameMenuItem);
contextMenu.MenuItems.Add(breakMenuItem);
contextMenu.MenuItems.Add(quitMenuItem);
shutdownPCIcon.ContextMenu = contextMenu;
shutdownPCIcon.Text = "ShutdownPC";
quitMenuItem.Click += QuitMenuItem_Click;
}
private void QuitMenuItem_Click(object sender, EventArgs e)
{
shutdownPCIcon.Dispose();
sleepingThread.Abort();
updatingThread.Abort();
this.Close();
}
public void sleepThread()
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(sleepThread));
}
else {
textBox1.Enabled = false;
textBox2.Enabled = false;
textBox3.Enabled = false;
button1.Enabled = false;
int totalMilliseconds = ((inputHours * 3600) + (inputMinutes * 60) + inputSeconds) * 1000;
Thread.Sleep(totalMilliseconds);
//Process.Start("shutdown", "/s /t 0");
richTextBox1.AppendText(String.Format("test"));
}
}
public void updateThread()
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(updateThread));
}
else {
int totalSeconds = (inputHours * 3600) + (inputMinutes * 60) + inputSeconds;
while (totalSeconds > 0)
{
TimeSpan time = TimeSpan.FromSeconds(totalSeconds);
string timeOutput = time.ToString(#"hh\:mm\:ss");
richTextBox1.AppendText(String.Format(timeOutput));
Thread.Sleep(1000);
richTextBox1.Clear();
totalSeconds--;
}
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
inputHours = Convert.ToInt32(textBox1.Text);
inputHours = int.Parse(textBox1.Text);
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
inputMinutes = Convert.ToInt32(textBox2.Text);
inputMinutes = int.Parse(textBox2.Text);
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
inputSeconds = Convert.ToInt32(textBox3.Text);
inputSeconds = int.Parse(textBox3.Text);
}
private void button1_Click(object sender, EventArgs e)
{
updatingThread = new Thread(new ThreadStart(updateThread));
updatingThread.Start();
sleepingThread = new Thread(new ThreadStart(sleepThread));
sleepingThread.Start();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
Using Invoke in the beginning of method that runs in separate thread is bad idea, because all code runs in GUI thread and lock it.
You should Invoke only GUI updating code!!!

C# Windows Forms Application | Cookie Clicker

Im trying to make a cookie maker!
it works great and all but every time i click on the cookie, it takes it about 2 clicks to add just one to the cookie count. I want to make the counting system go faster, since if i click 2 times a second, it will only count as one atm...
Code:
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;
using System.Threading;
namespace FormalCookie
{
public partial class Form1 : Form
{
int cnum = 0;
int add = 1;
public Form1()
{
InitializeComponent();
label1.Text = ("Price For Mouse:" + " 50");
textBox1.Text = ("Cookies:" + " " + cnum);
mouse.Enabled = false;
for (int i = 0; i< add; i++)
{
if (add > 1 && add % 2 == 0)
{
cnum += 1 * add;
}
Thread.Sleep(1000);
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
//Mouse
if (cnum >= add * add * 50)
{
cnum -= (add * 100);
add+=2;
}
}
private void button2_Click(object sender, EventArgs e)
{
Application.Restart();
}
private void button3_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
if (cnum >= (add * add * 50))
{
mouse.Enabled = true;
}
else
{
mouse.Enabled = false;
}
cnum += (add * add);
textBox1.Text = ("Cookies:" + " " + cnum);
label1.Text = ("Price For Mouse:" + " " + (add * add * 50));
}
private void label1_Click(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, MouseEventArgs e)
{
}
}
}

Ping over a period of Time

I have a windows form application that basically pings an ip and then returns an image with a tooltip that displays the rtt to that ip.
What i want to do is have the the form ping that ip every 20 seconds, so that the form and images change. If i could get that to work then I would like to some how store maybe 4 rtt's and then show an average of the 4 in the tooltip.
So far the form is only pinging once, I've played around with a timer but I don't really know what I am doing. Here is my code so far.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.NetworkInformation;
using System.ServiceProcess;
using System.Threading;
using System.ComponentModel;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
Ping pingClass = new Ping();
PingReply pingReply = pingClass.Send("10.209.123.123");
label4.Text = (pingReply.RoundtripTime.ToString());
//+ "ms");
label5.Text = (pingReply.Status.ToString());
if (Convert.ToInt32(label4.Text) > 0 && Convert.ToInt32(label4.Text) < 100)
this.pictureBox1.Load("greenLAT.png");
if (Convert.ToInt32(label4.Text) > 100 && Convert.ToInt32(label4.Text) < 200)
this.pictureBox1.Load("yellowLAT.png");
if (Convert.ToInt32(label4.Text) > 200 && Convert.ToInt32(label4.Text) < 1000)
this.pictureBox1.Load("redLAT.png");
ToolTip tt = new ToolTip();
tt.SetToolTip(this.pictureBox1, "Your current network delay is " + label4.Text + "ms");
timer1.Interval = 1000;
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
//MessageBox.Show("Timeout!");
Refresh();
}
}
}
Try this:
using System;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.Net;
using System.Windows.Forms;
using System.Net.NetworkInformation;
namespace DXWindowsApplication4
{
public partial class Form2 : Form
{
private readonly Timer _timer;
private readonly Ping _pingClass;
private readonly IPAddress _ipAddress;
private readonly int _timeout;
private Image _greenImage;
private Image _yellowImage;
private Image _redImage;
private int _pingCount;
private long _avgRtt;
public Form2()
{
InitializeComponent();
IPAddress.TryParse("98.138.253.109", out _ipAddress); // yahoo.com Ip address
_timer = new Timer();
_timeout = 3000;
_pingClass = new Ping();
_pingClass.PingCompleted += PingClassPingCompleted;
}
void PingClassPingCompleted(object sender, PingCompletedEventArgs e)
{
RefreshPing(e.Reply);
}
public void FormLoad(object sender, EventArgs e)
{
_timer.Tick += TimerTick;
_timer.Interval = 4000;
_timer.Start();
}
private void TimerTick(object sender, EventArgs e)
{
_pingClass.SendAsync(_ipAddress, _timeout);
}
private void RefreshPing(PingReply pingReply)
{
label4.Text = (pingReply.RoundtripTime.ToString(CultureInfo.InstalledUICulture));
label5.Text = (pingReply.Status.ToString());
_avgRtt = (_avgRtt * _pingCount++ + pingReply.RoundtripTime)/_pingCount;
if (Convert.ToInt32(label4.Text) > 0 && Convert.ToInt32(label4.Text) < 100)
{
SetImage(pictureBox1, Images.Green);
}
if (Convert.ToInt32(label4.Text) > 100 && Convert.ToInt32(label4.Text) < 200)
{
SetImage(pictureBox1, Images.Yellow);
}
if (Convert.ToInt32(label4.Text) > 200 && Convert.ToInt32(label4.Text) < 1000)
{
SetImage(pictureBox1, Images.Red);
}
ToolTip tt = new ToolTip();
tt.SetToolTip(pictureBox1, "Your average network delay is " + _avgRtt + "ms");
Refresh();
}
private void SetImage(PictureBox pBox, Images images)
{
switch (images)
{
case Images.Green:
if (_greenImage == null)
{
_greenImage = new Bitmap("greenImage.png");
}
pictureBox1.Image = _greenImage;
break;
case Images.Yellow:
if (_greenImage == null)
{
_yellowImage = new Bitmap("yellowImage.png");
}
pictureBox1.Image = _yellowImage;
break;
case Images.Red:
if (_redImage == null)
{
_redImage = new Bitmap("redImage.png");
}
pictureBox1.Image = _greenImage;
break;
default:
throw new InvalidEnumArgumentException("invalid enum name");
}
}
}
internal enum Images
{
Green,
Yellow,
Red
}
}

Caller ID Check if Caller has ended Call

I have a program that gets the incoming number, date and time. I want to check however if the person who is ringing me has put the phone down, how can I do this?
Below is the code which I currently have:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
namespace CallerID
{
public partial class CallerID : Form
{
int timesTicked = 0;
Point defaultLocation = new Point();
Point newLocation = new Point();
public CallerID()
{
InitializeComponent();
port.Open();
SetModem(); // SetModem(); originally went after WatchModem();
WatchModem();
//SetModem();
telephoneTimer.Interval = 16;
telephoneTimer.Tick += new EventHandler(telephoneTimer_Tick);
defaultLocation = pictureBox1.Location;
newLocation = pictureBox1.Location;
}
void telephoneTimer_Tick(object sender, EventArgs e)
{
if (timesTicked <= 2)
newLocation.X++;
if (timesTicked >= 4)
newLocation.X--;
if (timesTicked == 6)
{
timesTicked = 0;
pictureBox1.Location = defaultLocation;
newLocation = defaultLocation;
}
pictureBox1.Location = newLocation;
timesTicked++;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
WatchModem();
}
private SerialPort port = new SerialPort("COM3");
string CallName;
string CallNumber;
string ReadData;
private void SetModem()
{
port.WriteLine("AT+VCID=1\n");
//port.WriteLine("AT+VCID=1");
port.RtsEnable = true;
}
private void WatchModem()
{
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
}
public delegate void SetCallerIdText();
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
ReadData = port.ReadExisting();
//Add code to split up/decode the incoming data
//if (lblCallerIDTitle.InvokeRequired)
if (ReadData.Contains("NMBR"))
{
lblData.Invoke(new SetCallerIdText(() => lblData.Text = ReadData));
}
//else
// lblCallerIDTitle.Text = ReadData;
}
private void lblData_TextChanged(object sender, EventArgs e)
{
telephoneTimer.Start();
button1.Visible = true;
}
}
}
Please ignore the Timer Code as that is just for animation.
Have you tried the PinChanged event? Normally Carrier Detect will go low when the remote end disconnects.

Categories