Reminder using NotifyIcon and Timer C# - c#

I wrote some code to create a reminder. It should warn me through a notification when it's 10 am. To make this possible I created a DateTime object as DateTime.Now to get local time, and I used a timer to check every minute if it was the same time I wanted to be warned. The problem is that my application notify me only when form loads, but it doesn't when the time comes and the app is already running.
I'll leave you the code below. Thanks in advance.
public partial class Form1 : Form
{
NotifyIcon notify;
DateTime now;
public Form1()
{
InitializeComponent();
notify = new NotifyIcon()
{
Visible = true,
Icon = Properties.Resources.icon,
BalloonTipTitle = this.Text
};
now = DateTime.Now;
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Start();
}
private void notification()
{
while(true)
{
if (now.Hour.Equals(10) && now.Minute.Equals(30))
{
notify.BalloonTipText = "It's 10:30 am";
notify.ShowBalloonTip(3000);
timer1.Stop();
notify.Dispose();
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
notification();
}
}

Remove while(true) loop from notification. You have tick timer which will call notification regularly - and now you check the time infinitely after first tick.
now must be assigned on every tick, not at startup.
:
private void notification()
{
DateTime now = DateTime.Now;
if (now.Hour == 10 && now.Minute == 30)
{
notify.BalloonTipText = "It's 10:30 am";
notify.ShowBalloonTip(3000);
timer1.Stop();
}
}

Related

c# countdown timer pause

I've been trying to create a countdown timer(from 30 minutes) in a c# winforms application that has the ability to pause, and then resume from where the pause took place. I've tried a number of solutions to achieve this as I know there isn't a specific pause function of the System.Windows.Forms.Timer. I've scoured the internet but couldn't find anything that I could apply to my scenario. Everything I've tried either results in the timer starting again from 30 minutes, or continuing from where it would have been without a pause. This is driving me mad. Can anybody help or suggest an alternative way of doing this? This is my first post here so apologies if I've made any errors. Code below. I've commented out the code that is causing me an issue - I know it's not correct, either syntactically or logically.
public partial class FormWithTimer : Form
{
System.Windows.Forms.Timer timerx = new System.Windows.Forms.Timer();
DateTime startTime = DateTime.Now;
DateTime stopTime = DateTime.Now;
public FormWithTimer()
{
InitializeComponent();
TimerLabel.Text = "30:00";
}
private void Form1_Load(object sender, EventArgs e)
{
}
void timer_Tick(object sender, EventArgs e)
{
}
public void StartButton_Click(object sender, EventArgs e)
{
startTime = DateTime.Now;
BeginTextBox.Text = startTime.ToString();
TimerLabel.Visible = true;
timerx.Tick += (obj, args) =>
TimerLabel.Text = (TimeSpan.FromMinutes(30) - (DateTime.Now - startTime)).ToString("mm\\:ss");
timerx.Enabled = true;
}
public void PauseButton_Click(object sender, EventArgs e)
{
if (PauseButton.Text == "Pause")
{
timerx.Stop();
PauseButton.Text = "Start";
stopTime = DateTime.Now;
}
else
{
PauseButton.Text = "Pause";
timerx.Start();
TimerLabel.Visible = true;
//timerx.Tick += (obj, args) =>
// TimerLabel.Text = (TimeSpan.FromMinutes(30) - (DateTime.Now - (startTime - stopTime))).ToString("mm\\:ss");
timerx.Enabled = true;
}
}
}
I guess you are trying to have the timer continue where it was when it got paused.
To do that, I would suggest using stopTime for that matter:
In your "Pause-Unpause"- Routine:
public void PauseButton_Click(object sender, EventArgs e)
{
if (PauseButton.Text == "Pause")
{
timerx.Stop();
PauseButton.Text = "Start";
stopTime = DateTime.Now;
}
else
{
PauseButton.Text = "Pause";
startTime += (DateTime.Now - stopTime);
timerx.Start();
TimerLabel.Visible = true;
timerx.Enabled = true;
}
}

How can I send a message box if text hasn't been saved within X mins and the user wants to close the app?

Here's the pseudo code:
private void ForgetSave()
{
if (the SaveRegularly method hasn't been used within 3 mins)
MessageBox.Show("Would you like to save any changes before closing?")
......... the code continues.
}
else
{
this.close();
}
Does anybody know how to write the first line of the if statement?
Simply remember when the last save time was:
private const TimeSpan saveTimeBeforeWarning = new TimeSpan(0,1,0); //1 minute
private static DateTime _lastSave = DateTime.Now;
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if ((DateTime.Now - _lastSave) > saveTimeBeforeWarning)
{
if(MessageBox.Show("Would you like to save any changes before closing?") == DialogResult.Yes);
{
Save();
}
}
}
private void Save()
{
//save data
_lastSave = DateTime.Now
}
As Ahmed suggested you can use a timer and a flag to know when you have to display the message, I left you a piece of code to get you started
private const int SAVE_TIME_INTERVAL = 3 * 60 * 1000;
private bool iWasSavedInTheLastInterval = true;
private System.Windows.Forms.Timer timer;
public Form1()
{
InitializeComponent();
//Initialize the timer to your desired waiting interval
timer = new System.Windows.Forms.Timer();
timer.Interval = SAVE_TIME_INTERVAL;
timer.Tick += Timer_Tick;
timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
//If the timer counts that amount of time we haven't saved in that period of time
iWasSavedInTheLastInterval = false;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (iWasSavedInTheLastInterval == false)
{
MessageBox.Show("Would you like to save any changes before closing?");
}
}
private void btnSave_Click(object sender, EventArgs e)
{
//If a manual save comes in then we restart the timer and set the flag to true
iWasSavedInTheLastInterval = true;
timer.Stop();
timer.Start();
}

c# combo box with time for timer to elapse

I have a program that disables the lockscreen and stop a service in windows. I have two buttons Enable,Disable and a combo box that has preset times. When My program is ran and the user clicks Enable the program should disable lock screen until the user manually
clicks disable. What I am trying to accomplish is to keep the program from running all night long if user never hits disable. So by selecting a preset time out of the combo box the program will auto disable it self.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DateTime time = DateTime.Today;
for (DateTime _time = time.AddHours(16); _time < time.AddHours(18); _time = _time.AddMinutes(30))
{
comboBox1.Items.Add(_time.ToShortTimeString());
}
}
private static System.Timers.Timer _Timer;
private DateTime _lastRun = DateTime.Now;
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string strTime_Start = DateTime.Today.ToString();
string strTime_End = comboBox1.SelectedItem.ToString();
}
public void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
button2.Enabled = true;
_Timer = new System.Timers.Timer(10 * 60 * 1000);
_Timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
DisableLock();
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (strTime_End < DateTime.Now.Date) //I think this would be where I need to have strTime_End?
{
_Timer.Stop();
_lastRun = DateTime.Now;
}
}
}
The simplest solution in my mind would be to keep an instance variable for your stop time, and each combobox item you have sets this stop time, the timer_tick event would simply check if it has passed that time. A blank item in the combo box can clear the variable.
private DateTime timeToStop;
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
timeToStop = DateTime.Now.Add(DateTime.Parse(comboBox1.Text));
}
catch(Exception)
{
timeToStop = new DateTime(3000, 01, 01, 00, 00, 00);
}
}
public void disableButton_Click(object sender, EventArgs e)
{
_Timer.Stop();
_lastRun = DateTime.Now;
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (DateTime.Now >= timeToStop)
{
_Timer.Stop();
_lastRun = DateTime.Now;
// Disable regkey
}
}
from what i understood so far, you can just add :
comboBox1.Enabled = false;
when the time is elapsed, i.e. in the event.

The timer works fine if it's coded inside a button_click event handler, but it doesn't work if it is inside a method

I found timer code from a web site and used it in my application and it works fine if I use the timer code inside a button_click handler, but I need to use the timer when I call a method, so I did copy and paste the same code from the button_click into the method but the timer always gives me zero. How do I fix it?
The following is the timer code.
public partial class Form1 : Form
{
//Timer decleration
DateTime startTime, StopTime;
TimeSpan stoppedTime;
bool reset;
bool startVariabl = true;
// The rest of the code..
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
if (startVariable) startMethod();
//
//The rest of the code...
}
private void startMethod()
{
//Timer
tmDisplay.Enabled = true;
// Reset display to zero
reset = true;
lblElapsed.Text = "00:00.00.0";
// Start timer and get starting time
if (reset)
{
reset = false;
startTime = DateTime.Now;
stoppedTime = new TimeSpan(0);
}
else
{
stoppedTime += DateTime.Now - StopTime;
}
}
private void tmDisplay_Tick(object sender, EventArgs e)
{
DateTime currentTime;
//Determine Ellapsed Time
currentTime = DateTime.Now;
// Display Time
lblElapsed.Text = HMS(currentTime - startTime - stoppedTime);
}
private string HMS(TimeSpan tms)
{
//Format time as string; leaving off last six decimal places.
string s = tms.ToString();
return (s.Substring(0, s.Length - 6));
}
I am new C# learner.
as keyboardP suggested in a comment you should add this line:
tmDisplay.Tick += new EventHandler(tmDisplay_Tick);
usually Tick handler is set once (unless you need to switch it to other callback or nullify it for some reason) so I would add it in your Form constructor assuming that timer is already created then or after timer initialization if you do it in some method.

Label displaying Timespan disappearing in XP but not in newer Windows versions

I have a stopwatch timer that I've added to my program. It's working fine on my Win 7 machine, and on the Vista machines I've tried, but in XP, the hrs and mins zeros disappear when the timer starts, but will come back if I reset the timer. Here's all of my code that I have for the timer. I've removed everything that didn't seem necessary to diagnose the problem:
DateTime startTime, stopTime;
TimeSpan stoppedTime;
bool reset;
private void btnStopwatchStart_Click(object sender, EventArgs e)
{
// Start timer and get starting time
if (reset)
{
reset = false;
startTime = DateTime.Now;
stoppedTime = new TimeSpan(0);
}
else
{
stoppedTime += DateTime.Now - stopTime;
}
stopwatchTimer.Enabled = true;
}
private void btnStopwatchReset_Click(object sender, EventArgs e)
{
// Reset displays to zero
reset = true;
lblElapsed.Text = "00:00:00";
}
private void btnStopwatchPause_Click(object sender, EventArgs e)
{
// Stop timer
stopTime = DateTime.Now;
stopwatchTimer.Enabled = false;
}
private void stopwatchTimer_Tick(object sender, EventArgs e)
{
DateTime currentTime;
// Determine elapsed and total times
currentTime = DateTime.Now;
// Display times
lblElapsed.Text = HMS(currentTime - startTime - stoppedTime);
}
private string HMS(TimeSpan tms)
{
// Format time as string, leaving off last six decimal places
string s = tms.ToString();
return (s.Substring(0, s.Length - 6));
}
Older version of .NET, maybe? Your HMS() function critically depends on the number of digits generated by TimeSpan.ToString(). Here's a better way to format it:
private static string HMS(TimeSpan tms) {
return new DateTime(tms.Ticks).ToString("H:mm:ss");
}

Categories