SImulated mouse scrolling is processed after sleeps - c#

I am using
for (int i = 0; i < 10; i++)
{
mouse_event(MOUSEEVENTF_WHEEL, 0, 0, -10, 0);
System.Threading.Thread.Sleep(1000);
}
to scroll down a bit then wait a second the scroll and so on. However, it seems to wait 10 seconds then scroll down -100.
I am not sure if this is relevant but I am trying to get it to scroll down a page in a web browser as part of a windows form (once you scroll to the bottom the page loads more and you can scroll again).

the problem is that your GUI freezes and is not updated for the duration of the for loop, because it is running on the same thread. To See the changes every second you need to run it on a background thread.
You can also use a System.Timers.Timer to do that job. Set it up as
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 1000;
timer.AutoReset = true;
and hook up the Elapsed event in which you handle the scrolling
timer.Elapsed += Timer_Elapsed;
timer.Start();
you would also need a counter like in your for-loop. Count down until 0 with it in the event handler
int counter = 10;
private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if(counter > 0)
{
mouse_event(MOUSEEVENTF_WHEEL, 0, 0, -10, 0);
counter--;
}
else
{
System.Timers.Timer t = sender as System.Timers.Timer;
t.Stop();
}
}
This way you can stop the timer after 10 iterations
As suggested by Jakub DÄ…bek you can also use System.Windows.Forms.Timer. This would look like this:
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
timer.Interval = 1000;
timer.Tick += Timer_Tick;
timer.Start();
private void Timer_Tick(object sender, EventArgs e)
{
// here the same code as above
}

Related

Using timer in windows form application

I am new to coding and are having trouble.
I want to use a timer that will start upon pressing ScatterMode tab, it will start counting 4sec before running "Dosomething" function. This cycle will repeat itself until i decide to stop the program. But the problem i get is, this code only run correctly for like 2loop, after that the timer sort of go crazy LOL.
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
//ScatterMode Tab
private void Scatter_modeToolStripMenuItem_Click(object sender, EventArgs e)
{
timer.Interval = 4000;
timer.Enabled = true;
timer.Tick += new EventHandler(Dosomething);
timer.Start();
}
private void Dosomething (object sender, EventArgs e)
{
timer.Stop();
timer.Enabled = false;
Grab.buffer(out buffer, out status, 6000);
Scatter_mode(buffer);
pictureBox1.Refresh();
int done_grab = 1;
if (doneGrab == 1)
{
timer.Interval = 4000;
timer.Enabled = true;
timer.Tick += new EventHandler(Scatter_modeToolStripMenuItem_Click);
timer.Start();
done_grab = 0;
}
}
Adding a new event handler to a timer, to handle its tick event, inside the handler for the tick event will indeed cause the timer to go "crazy". Every time the timer raises its event, another event handler (that responds to events raised) will be added. This means the next time the timer ticks, the event code will run twice. Two new event handlers will be added. Next time the timer ticks, the code will run 4 times. 4 event handlers will be added ... and so on
Remove this line from your code:
timer.Tick += new EventHandler(Scatter_modeToolStripMenuItem_Click);
And move this line into your form's constructor:
timer.Tick += new EventHandler(Dosomething);
You only want to wire this event handler up once. Every time the timer's interval elapses, the code will run, once :)
I'll also do a bit of a peer review of your code, see the comments:
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
//ScatterMode Tab
private void Scatter_modeToolStripMenuItem_Click(object sender, EventArgs e)
{
timer.Interval = 4000; //can go in the constructor also; don't need to set repeatedly
timer.Enabled = true;
timer.Tick += new EventHandler(Dosomething); //move to constructor
timer.Start(); //this isn't needed - you already Enabled the timer, which started it
}
private void Dosomething (object sender, EventArgs e)
{
timer.Stop(); //use this
timer.Enabled = false; //or this. It's not required to do both
Grab.buffer(out buffer, out status, 6000); //if these lines crash then your timer will
Scatter_mode(buffer); //only restart if the toolstripmenuitemclick
pictureBox1.Refresh(); //above runs.. is it what you wanted?
int done_grab = 1; //not needed
if (doneGrab == 1) //this will always evaluate to true, it is not needed
{
timer.Interval = 4000; //the interval is already 4000, not needed
timer.Enabled = true; //careful; your timer may stop forever if the code above crashes
timer.Tick += new EventHandler(Scatter_modeToolStripMenuItem_Click); //remove
timer.Start(); //not needed
done_grab = 0; //not needed
}
}

How to pause timer in windows phone?

In this code after starting timer again it starts from the current value instead of the vale it stopped. How to pause this timer?
public Page1()
{
InitializeComponent();
_rnd = new Random();
_timer = new DispatcherTimer();
_timer.Tick += new EventHandler(TimerTick);
_timer.Interval = new TimeSpan(0, 0, 0, 1);
}
void TimerTick(object sender, EventArgs e)
{
var time = DateTime.Now - _startTime;
txtTime.Text = string.Format(Const.TimeFormat, time.Hours, time.Minutes, time.Seconds);
}
public void NewGame()
{
_moves = 0;
txtMoves.Text = "0";
txtTime.Text = Const.DefaultTimeValue;
Scrambles();
while (!CheckIfSolvable())
{
Scrambles();
}
_startTime = DateTime.Now;
_timer.Start();
//GridScrambling.Visibility = System.Windows.Visibility.Collapsed;
}
private void Pause_Click(object sender, System.Windows.RoutedEventArgs e)
{
// TODO: Add event handler implementation here.
NavigationService.Navigate(new Uri("/Page4.xaml", UriKind.Relative));
_timer.Stop();
}
private void Play_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
// TODO: Add event handler implementation here.
_timer.Start();
}
As this says that the Stop method only changes the IsEnabled property and this says that this property only prevents the Tick event to be raised, I don't think that there is a method to simply 'pause' the timer. The best way is to reinitialize the timer each time you have "paused" it, if you really want it to start clean again.
But I do not think that this is you real problem. When you pause your game the timer stops working. When you continue it the timer starts working again. When you now try the calculate the time from THIS moment till the start time, then you make a big mistake: you have to ignore the paused time. Because when you play the game 2s, then pause it for 10s and then continue the game, the timer shows 12s, instead of 2s, doesn't it? Maybe you should store the paused times in a variable and substract that from the real game time.

C# timer I can speed up but not slow down

I have a timer event setup and I would like to change how often the timer event happens by reading a number from a text box. If the box is '10' and you click the update button the event would trigger every 10ms then if you changed to '100' and clicked it would happen every 100ms and so on.
When I run the program however, i can speed up the event frequency (e.g. 100ms to 10ms) but I cannot slow it down (e.g. 10ms to 100ms). Here is the piece of my code that changes the timer when I click:
private void TimerButton_Click(object sender, EventArgs e)
{
getTime = ImgTimeInterval.Text;
bool isNumeric = int.TryParse(ImgTimeInterval.Text, out timerMS); //if number place number in timerMS
label2.Text = isNumeric.ToString();
if (isNumeric)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Enabled = false;
timer.Interval = timerMS;
timer.Elapsed += new ElapsedEventHandler(timerEvent);
timer.AutoReset = true;
timer.Enabled = true;
}
}
public void timerEvent(object source, System.Timers.ElapsedEventArgs e)
{
label1.Text = counter.ToString();
counter = (counter + 1) % 100;
}
If anyone knows what I may be doing wrong it would be greatly appreciated.
The problem with this code is, that you create a new Timer each time you click the button. Try to create the timer outside the method. You think it's only goes faster, but instead multiple timers trigger the timerEvent
private System.Timers.Timer _timer;
private void CreateTimer()
{
_timer = new System.Timers.Timer();
_timer.Enabled = false;
_timer.Interval = 100; // default
_timer.Elapsed += new ElapsedEventHandler(timerEvent);
_timer.AutoReset = true;
_timer.Enabled = true;
}
private void TimerButton_Click(object sender, EventArgs e)
{
bool isNumeric = int.TryParse(ImgTimeInterval.Text, out timerMS); //if number place number in timerMS
label2.Text = isNumeric.ToString();
if (isNumeric)
{
_timer.Interval = timerMS;
}
}
public void timerEvent(object source, System.Timers.ElapsedEventArgs e)
{
label1.Text = counter.ToString();
counter = (counter + 1) % 100;
}
Make sure that the CreateTimer is called in the constructor/formload. Also you can now stop the timer within another button event. With _timer.Enabled = false;
You're always creating a new timer and never stopping the old timer. When you "change" it from 100 to 10 your 100ms timer is still firing every 100 ms, so every 100ms two timers are firing at around the same time.
You need to "remember" the old timer so that you can stop it. Or, better yet, just have only one timer that you change the interval on.
private System.Timers.Timer timer = new System.Timers.Timer();
public Form1()
{
timer.Enabled = false;
timer.AutoReset = true;
timer.Elapsed += timerEvent;
}
private void TimerButton_Click(object sender, EventArgs e)
{
getTime = ImgTimeInterval.Text;
bool isNumeric = int.TryParse(ImgTimeInterval.Text, out timerMS); //if number place number in timerMS
label2.Text = isNumeric.ToString();
if (isNumeric)
{
timer.Interval = timerMS;
timer.Enabled = true;
}
}
Well the basic problem is that you're building a new one every time. Make a private timer:
private System.Timers.Timer _timer = new System.Timers.Timer();
and then fix it up when the button is clicked:
if (isNumeric)
{
_timer.Stop();
_timer.Interval = timerMS;
_timer.Start();
}
and then in the .ctor, do this:
_timer.Elapsed += new ElapsedEventHandler(timerEvent);
Now you have a single timer that you are just modifying as the user changes the value in the text box.

C# timer stop after some number of ticks automatically

How to stop a timer after some numbers of ticks or after, let's say, 3-4 seconds?
So I start a timer and I want after 10 ticks or after 2-3 seconds to stop automatically.
Thanks!
You can keep a counter like
int counter = 0;
then in every tick you increment it. After your limit you can stop timer then. Do this in your tick event
counter++;
if(counter ==10) //or whatever your limit is
yourtimer.Stop();
When the timer's specified interval is reached (after 3 seconds), timer1_Tick() event handler will be called and you could stop the timer within the event handler.
Timer timer1 = new Timer();
timer1.Interval = 3000;
timer1.Enabled = true;
timer1.Tick += new System.EventHandler(timer1_Tick);
void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop(); // or timer1.Enabled = false;
}
i generally talking because you didn't mention which timer, but they all have ticks... so:
you'll need a counter in the class like
int count;
which you'll initialize in the start of your timer, and you'll need a dateTime like
DateTime start;
which you'll initialize in the start of your timer:
start = DateTime.Now;
and in your tick method you'll do:
if(count++ == 10 || (DateTime.Now - start).TotalSeconds > 2)
timer.stop()
here is a full example
public partial class meClass : Form
{
private System.Windows.Forms.Timer t;
private int count;
private DateTime start;
public meClass()
{
t = new Timer();
t.Interval = 50;
t.Tick += new EventHandler(t_Tick);
count = 0;
start = DateTime.Now;
t.Start();
}
void t_Tick(object sender, EventArgs e)
{
if (count++ >= 10 || (DateTime.Now - start).TotalSeconds > 10)
{
t.Stop();
}
// do your stuff
}
}
Assuming you are using the System.Windows.Forms.Tick. You can keep track of a counter, and the time it lives like so. Its a nice way to use the Tag property of a timer.
This makes it reusable for other timers and keeps your code generic, instead of using a globally defined int counter for each timer.
this code is quiet generic as you can assign this event handler to manage the time it lives, and another event handler to handle the specific actions the timer was created for.
System.Windows.Forms.Timer ExampleTimer = new System.Windows.Forms.Timer();
ExampleTimer.Tag = new CustomTimerStruct
{
Counter = 0,
StartDateTime = DateTime.Now,
MaximumSecondsToLive = 10,
MaximumTicksToLive = 4
};
//Note the order of assigning the handlers. As this is the order they are executed.
ExampleTimer.Tick += Generic_Tick;
ExampleTimer.Tick += Work_Tick;
ExampleTimer.Interval = 1;
ExampleTimer.Start();
public struct CustomTimerStruct
{
public uint Counter;
public DateTime StartDateTime;
public uint MaximumSecondsToLive;
public uint MaximumTicksToLive;
}
void Generic_Tick(object sender, EventArgs e)
{
System.Windows.Forms.Timer thisTimer = sender as System.Windows.Forms.Timer;
CustomTimerStruct TimerInfo = (CustomTimerStruct)thisTimer.Tag;
TimerInfo.Counter++;
//Stop the timer based on its number of ticks
if (TimerInfo.Counter > TimerInfo.MaximumTicksToLive) thisTimer.Stop();
//Stops the timer based on the time its alive
if (DateTime.Now.Subtract(TimerInfo.StartDateTime).TotalSeconds > TimerInfo.MaximumSecondsToLive) thisTimer.Stop();
}
void Work_Tick(object sender, EventArgs e)
{
//Do work specifically for this timer
}
When initializing your timer set a tag value to 0 (zero).
tmrAutoStop.Tag = 0;
Then, with every tick add one...
tmrAutoStop.Tag = int.Parse(tmrAutoStop.Tag.ToString()) + 1;
and check if it reached your desired number:
if (int.Parse(tmrAutoStop.Tag.ToString()) >= 10)
{
//do timer cleanup
}
Use this same technique to alternate the timer associated event:
if (int.Parse(tmrAutoStop.Tag.ToString()) % 2 == 0)
{
//do something...
}
else
{
//do something else...
}
To check elapsed time (in seconds):
int m = int.Parse(tmrAutoStop.Tag.ToString()) * (1000 / tmrAutoStop.Interval);

Timer starts only after the Form is closed

I am currently working on a C# application that runs on a Windows CE 5 device with MS Compact Framework 2.0.
In this application I call a singleton dialog from a keyboard-hook asynchronously via BeginInvoke:
this.BeginInvoke((ThreadStart)delegate()
{
DlgX.getInstance().display(TaskController.getInstance().getActiveTask().getValues(), true);
});
In the display method of the dialog I want to set the focus to a certain control. As the Win CE device is very slow, I have to use a timer to delay the Focus() execution:
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
timer.Interval = 600;
timer.Enabled = true;
timer.Tick += (EventHandler)delegate(object obj, EventArgs args)
{
button1.Focus();
timer.Dispose();
};
Unfortunately this does not work. The timer gets executed as soon as I close the dialog.
What am I doing wrong?
Thank you in advance for any help!
edit:
This is the whole display() method of the dialog:
public void display(List<InputRow> fvList, bool validate)
{
this.fvList = fvList;
ctlCount = (fvList.Count > 5 ? 5 : fvList.Count);
for (int i = 0; i < ctlCount; i++)
{
//some 100% irrelevant stuff
}
button1.KeyDown += new KeyEventHandler(btnOK_KeyDown);
button1.Click += new EventHandler(btnOK_Click);
if (!this.Visible)
{
ShowDialog();
}
if (validate)
{
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
timer.Interval = 600;
timer.Enabled = true;
timer.Tick += (EventHandler)delegate(object obj, EventArgs args)
{
button1.Focus();
timer.Dispose();
};
}
}
The timer instantiation and enabling is evaluated when you close your form, because ShowDialog is synchronous. You should put your timer before your ShowDialog

Categories

Resources