My application is set to go to sleep when a notification balloontip is clicked and this process is all looped. This works, but when I awaken my computer, it goes to sleep shortly thereafter (this has a slight time delay, but as this takes as long as it normally takes for my computer to go to sleep, I wouldn't give this any consideration). I've removed this snippet from my overall program, and the program then works perfectly fine, making me think that there's something in this code that makes the computer go to sleep. Furthermore, in case one of the flags controlling the loops is reset, I've reset those flags, but the problem keeps happening. In case (for some strange reason) the boolean operators were impacting it, I've changed them in all the combinations I could, and it still didn't work! I've tried adding in a command to prevent the computer from going to sleep, but that didn't work either. Any suggestions? Much appreciated.
for (; ; )
{
bool for3 = false;
for (; ; )
{
notifyIcon.ShowBalloonTip(10000);
System.Threading.Thread.Sleep(10000);
Application.DoEvents();
if (loopVariable)
for3 = true;
if (for3) break;
System.Threading.Thread.Sleep(60000);
}
loopVariable = false;
for3 = false;
DateTime timeOnSleep = DateTime.Now;
Application.SetSuspendState(PowerState.Suspend, false, false);//this is the annoying code
DateTime timeOnWake = DateTime.Now;
TimeSpan time = timeOnWake - timeOnSleep;
var minutes = time.TotalMinutes;
Math.Round(time.TotalMinutes, MidpointRounding.AwayFromZero);
double dMins = minutes;
try
{
int iNumber = System.Convert.ToInt32(dMins);
}
catch (System.OverflowException)
{
if (dMins >= 40)
break;
}
}
private static bool loopVariable = false;
void notifyIcon_BalloonTipClicked(object sender, EventArgs e)
{
loopVariable = true;
}
If you find yourself using doevents, you're likely doing something wrong. If you needed to run a loop like that use do {} rather than for (;;). In any case, you don't need either of those things. If this isn't supposed to run infinitely, you can disable the timer just before calling Application.SetSuspendState.
void Main()
{
Timer timer = new Timer();
timer.Tick += new EventHandler(timer_Tick);
timer.Interval = 30000; //How often you want to show the tooltip?
timer.Enabled = true;
}
void notifyIcon1_BalloonTipClicked(object sender, EventArgs e)
{
Application.SetSuspendState(PowerState.Suspend, false, false);
}
void timer_Tick(object sender, EventArgs e)
{
notifyIcon1.ShowBalloonTip(10000);
}
Related
bool elapsed = false;
private void timerElapsed(object sender, System.Timers.ElapsedEventArgs e)
{
elapsed = true;
}
private void WorkerThreadFunction()
{
Timer _timer = new System.Timers.Timer(60000);
_timer.Elapsed += timerElapsed;
_timer.AutoReset = false;
while (!elapsed)
{
// Do something...
Thread.Sleep(50);
}
}
How is the global variable "elapsed" reacting? Is it possible to run more separate WorkerThreads with timers?
Of course it is possible to run more separate WorkerThreads. Each one will have it's own timer. There shouldn't be a problem.
The variable bool elapsed will be set to true by the first Thread that finishes its job, and it will stay true until some other process sets it to false. If you are unlucky some thread might even not start its job because the first on has set your elapsed to true
EDIT:
it seems that your thread job is encapsulated.
So you could actually also just use a stopwatch, if you don't need to access global variables from within the thread
private void WorkerThreadFunction()
{
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Start();
while(watch.ElapsedMilliseconds < 60000)
{
// Do something...
Thread.Sleep(50);
}
watch.Stop();
}
I have no idea why this code does not work.
The timer just seams to freeze everything. As far as I know, the timer is sent to a newly created thread. I've tried locking on tick, but no luck.
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public int CountUp = 0;
public Form1()
{
InitializeComponent();
label1.Text = "Click To Start Timer";
timer1.Enabled = false;
timer1.Stop();
timer1.Interval = 1000;
}
private void button1_Click(object sender, EventArgs e)
{
bool Toggled = false;
if (!Toggled)
{
timer1.Enabled = true;
Toggled = true;
}
else
{
timer1.Enabled = false;
Toggled = false;
label1.Text = "Timer Stopped";
CountUp = 0;
}
while(Toggled){
label1.Text = "Timer1 Running";
}
}
private void timer1_Tick(object sender, EventArgs e)
{
//lock (label2.Text) <- froze the program immediately
//{
// CountUp++;
// string CurrentTime = CountUp.ToString();
// label2.Text = CurrentTime;
//}
CountUp++;
string CurrentTime = CountUp.ToString();
label2.Text = CurrentTime;
//CurrentTime = timer1.ToString() = Garbage & freeze.
}
}
}
Any suggestions? It may be the key to solving this question.
The while(Toggled){ .. } code will freeze the interface and hang the program as it blocks the UI thread. However, the Forms.Timer, which relies on the UI event queue being processed, will never fire due to the blocking loop - as such, the flag variable will never be "reset".
While one of the threaded timers could be used, it would still result in an un-responsive UI. The solution is to design [WinForm] programs to react to events, such as when the timer starts and when it stops1.
1 There are actually no start/stop events per-se, but do the actions when the timer is started or stopped by the code. For example,
private void button1_Click(object sender, EventArgs e)
{
if (!timer1.Enabled) {
CountUp = 0;
timer1.Enabled = true;
label1.Text = "Timer1 Running";
} else {
timer1.Enabled = false;
label1.Text = "Timer1 Stopped (Manual)";
}
}
// Later on, when a tick occurs and the timer should end..
// The timer callback runs on the UI thread it was created on.
private void timer1_Tick(object sender, EventArgs e)
{
CountUp++;
if (CountUp > 10) {
timer1.Enabled = false;
label1.Text = "Timer1 Stopped (Time up)";
}
}
There is no need to use lock at all because all of the code should be running on the UI thread.
I have to start timer on the event when eyes are closed for a certain duration.If timer is elapsed Screen turns Off.If eye open before timer is elapsed timer is stopped and screen turns On.
ComputationOfTimer(); monitors whether eyes are open/closed. This is working fine as I am getting right feedback in console.
private void ComputationOfTimer()
{
if (blink[0] == 100) //If eye Closed detected
{
ctrlTimerStop = 3;
ctrlTimerStart = ctrlTimerStart - 1;
System.Console.Write("\n\t Eyes Closed");
timerStarting();
}
else //If eyes are open before timer is elapsed
//we have to stop timer
{
ctrlTimerStart = 5;
ctrlTimerStop -= 1;
//System.Console.Write("\n\t\t\t\t\t Opened");
timerStopping();
}
}
timerStarting() starts the timer
public void timerStarting()
{
if (ctrlTimerStart == 0)
{
screenOffTimer.Interval = 3000;
screenOffTimer.Elapsed += screenOffTimer_Tick_ScreenOff;
screenOffTimer.AutoReset=false;
if (!screenOffTimer.Enabled) //Starts timer only once
{
screenOffTimer.Enabled = true;
System.Console.Write("Timer Chaloo Hai");
}
}
}
Logic of Screen Off and Sleep
void screenOffTimer_Tick_ScreenOff(object sender, EventArgs e)
{
System.Console.Write("Eyes Closed For long time bro!");
Beep(440, 1000); // Concert A, for 1 second
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, MONITOR_OFF);
//as eyes are still closed send pc to Sleep start one more timer
gotoSleepTimer.Interval = 10000;
gotoSleepTimer.Elapsed += gotoSleepTimer_Tick_SleepOff;
gotoSleepTimer.AutoReset = false;
if (!gotoSleepTimer.Enabled)
{
gotoSleepTimer.Start();
}
}
void gotoSleepTimer_Tick_SleepOff(object sender, EventArgs e)
{
System.Console.Write("So rahe hain bhai ab");
Beep(440, 2000); // Concert A, for 1 second
System.Windows.Forms.Application.SetSuspendState(PowerState.Suspend, false, false);
}
timerStopping(); to stop the timer if Eyes are opened earlier
public void timerStopping() //To stop timer when Eyes Open
{
if (ctrlTimerStop == 0)
{
//to do timer stop logic
if (screenOffTimer.Enabled)
{
screenOffTimer.Stop();
System.Console.Write("Timer Band Ho Gaya");
}
//System.Windows.MessageBox.Show("Timer Stopped");
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, MONITOR_ON);
if (gotoSleepTimer.Enabled)
{
gotoSleepTimer.Stop();
}
}
}
Timer is not firing even after time is elapsed.I tried DispatcherTimer before but that is to update WPF UI and I have different objective.
Declaration part:
System.Timers.Timer screenOffTimer = new System.Timers.Timer();
System.Timers.Timer gotoSleepTimer = new System.Timers.Timer();
try
EventTabTimer.Elapsed += new ElapsedEventHandler(gotoSleepTimer_Tick_SleepOff);
I could not see screenOffTimer.Start() in the code attached in question. May be thats the problem
Thanks
I'm trying to create a Windows Form application that searches for a string and has three possible scenarios:
String 1 found - wait
String 2 found - stop
Else - Perform action and wait 1 minute
I am encountering my problem only on the times when it is expected to wait. When this happens, the newTimer_Tick starts to tick every second. I have tried disabling the timer when it ticks and a few other things but none appeared to work. Below is the code:
public void Action(string result)
{
if (result.Contains("string1"))
{
// Check again in 10 + x seconds
int n = new Random().Next(0, 5000);
int newtime = 10000 + n;
newTimer.Tick += new EventHandler(newTimer_Tick);
newTimer.Interval = newtime;
newTimer.Enabled = true;
}
else if (result.Contains("string2"))
{
// Turn off
newTimer.Enabled = false;
}
else
{
// Perform action and tick again in 1min + x seconds
action1();
int n = new Random().Next(0, 5000);
int newtime = 600000 + n;
newTimer.Tick += new EventHandler(newTimer_Tick);
newTimer.Interval = newtime;
newTimer.Enabled = true;
}
}
private void newTimer_Tick(object sender, EventArgs e)
{
Action( result );
}
What have I done wrong?
Each time the following line is called, an new instance of the event handler newTimerTick is added to the invocation list for the Tick event:
newTimer.Tick += new System.EventHandler(newTimer_Tick);
So every time the time tick goes off newTimerTick is going to be called multiple times, which is going to give you unexpected results.
Configure your event handler once only. In the constructor would be a sensible place.
Have you tried to stop the timer with the Timer.Stop method?
Btw: I don't think you need to reassign the Tick event from the newTimer unless you don't create a new Timer everytime.
I think what you were missing is that you have to stop your timer since you don't actually want it to keep for more than one interval. You seem to want to run it once, check on the result and then decide if you want to keep running it or not. Here's the code:
public void action(string result)
{
int n = new Random().Next(0, 5000);
Boolean blActivateTimer = true;
Timer timer = new Timer();
timer.Tick += timer_Tick;
if (!result.Contains("string1") && !result.Contains("string2"))
{
n += 600000;
action1();
}
else
{
if (result.Contains("string1"))
{
n += 10000;
}
else
{
blActivateTimer = false;
}
}
if (blActivateTimer)
{
timer.Start();
}
}
void action1()
{
}
void timer_Tick(object sender, EventArgs e)
{
Timer t = (Timer)sender;
t.Stop();
action(result);
}
I'm having a little bit of trouble figuring out the best way to display 1 character at a time on the console using a timer. The idea is to have an RPG style message stream across the screen instead of being pasted all at once.
private static System.Timers.Timer aTimer;
public void DisplayTime()
{
aTimer = new System.Timers.Timer(5000);
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.AutoReset = false;
aTimer.Enabled = true;
Console.ReadLine();
}
public void OnTimedEvent(object source, ElapsedEventArgs e)
{
string text;
text = "This is a test";
char[] message = new char[text.Length];
message = text.ToCharArray();
for (int i = 0; i < message.Length; i++)
{
Console.Write(message[i]);
}
}
That is what I currently have which just delays displaying the message for 5 seconds. I'm trying to avoid using Thread.Sleep if possible because from what I've read that is a big no no. I know I need to create a delay in the for loop to get the effect i need but is this really the best way to go about it?
This is a great place for using a lambda.
public void DisplayTime(string message) {
var index = 0;
var timer = new System.Timers.Timer(5000);
timer.Elapsed += delegate {
if (index < message.Length) {
Console.Write(message[index]);
index++;
} else {
timer.Enabled = false;
timer.Dispose();
}
};
timer.Enabled = true;
}
Now you can just call DisplayTime("the message") and it will slowly write out the message one character every 5 seconds and clean up the timer when it's finished
Use Thread.Sleep(). It will provide just what you need for, without any drawbacks for you. What you heard about Sleep() is completely out of context and it doesn't apply to your situation.
You need to keep track of where you are in your character stream - It seems like you want to display just one character at a time and then pause a little, until you have displayed all characters. A timer would be perfect for this - you will have to keep track of the message and the current position in the message as instance variables though:
private int messagePosition = 0;
private string message = "This is a test";;
public void OnTimedEvent(object source, ElapsedEventArgs e)
{
if(messagePosition < message.Length)
{
Console.Write(message[messagePosition]);
messagePosition++;
}
else
aTimer.Enabled = false;
}