I use the webbrowser control of .NET to open piles of urls,and the loop is called in the DocumentCompleted event.
Now I want to control the timeout.So I use a timer,and when timeout it will stop the webbrowser using the stop() function.
The question is: it seems that the stop function fires the DocumentCompleted event sometimes.So if the timer calls the next loop after stop the webbrowser,error happens.And if it doesn't call the next loop,sometimes the loop will be stopped in the middle.
The procedure like this(codes not related are deleted):
private string[] urls;//urls are stored here
private int index = 0;//next url index
private void loopFunc()
{
timer.Enabled = true;
wb.navigate(urls[index]);
index++;
return;
}
private void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
loopFunc();
}
private void timer1_Tick(object sender, EventArgs e)
{
wb.stop();
//loopFunc() or not?
}
I don't know for sure whether it fires the event or not,and I found nothing via google.
If I have understood your situation clearly this could solve your problem:
Timer On ---> loopFunc() --> goto url --> oncomplete -> start timer again -->
|
|---> Stop timer so it doesn't call loopFunc again
So stop the timer after loopFunc, when the download completes, loopFunc is called again:
private void loopFunc()
{
timer.Enabled = true;
wb.navigate(urls[index]);
index++;
timer.stop(); //<<<<<
return;
}
And your tick should be:
private void timer1_Tick(object sender, EventArgs e)
{
loopFunc();
}
Then start your timer again on document complete:
private void wb_DocumentCompleted(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
wb.Stop();
timer.Start();
}
Related
In this example I'm using 1 button and web browser in VB using C#
I simply want to hit the button once then have it go to bing, wait 2 seconds, then go to google. Every method I've seen when I try it always has the pause or pauses at the beginning and not between navigation. Here's what I have. Thanks in advance.
public void button1_Click(object sender, EventArgs e)
{
WebBrowser1.Navigate("http://www.bing.com");
Thread.sleep(2000);
WebBrowser1.Navigate("http://www.google.com");
}
Subscribe to the DocumentCompleted event and navigate to the second page there:
private void LoadPages()
{
WebBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser1_DocumentCompleted);
WebBrowser1.Navigate("http://www.bing.com");
}
void WebBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser1.Navigate("http://www.google.com");
// Might want to dispose of the webbrowser instance or else
// this event will fire again for the above call to `Navigate()`
// and you'll end up in a loop.
((WebBrowser)sender).Dispose();
// Or you could unsubscribe to the event if you still need the browser instance
WebBrowser1.DocumentCompleted -= WebBrowser1_DocumentCompleted;
}
private void btnProveri_Click(object sender, EventArgs e)
{
lblRezultat.Text = DateTime.Now.ToString();
timer1.Interval = 1800;
timer1.Start();
MessageBox.Show(DateTime.Now.ToString());
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Enabled = true;
timer1.Interval = 1800;
}
I am a newbie trying to learn timers and this is my code above. I want to make a Timer which last 1,8 seconds. Then I call it inside the button when it's clicked and the first time the label is set to specific date and then i set interval to the timer and start it, but the messagebox outputs the same time (no delay at all).
That's because you're displaying the message box from within the same code that creates the timer. Effectively:
buttonClick:
Populate some text field.
Start timer so that it calls timerTick in 1.8 seconds
Display message box
timerTick:
Restart timer so it calls this function in 1.8 seconds.
As you can see, the message box is displayed at the time you press the button, not when the timer fires. When the timer fires, all you do is set it to fire again in another 1.8 seconds, but you don't actually do anything else at that point.
If you want it to display after the timer fires, it will have to be done in the timer function timer1_Tick. But you may want to be careful with that, it's possible you may end up with a rather large number of dialog boxes.
It looks like you want to do something like this:
private void btnProveri_Click(object sender, EventArgs e)
{
lblRezultat.Text = DateTime.Now.ToString();
var timer = new System.Timers.Timer(1800);
timer.Start();
timer.Elapsed += timer1_Tick;
}
private void timer1_Tick(object sender, System.Timers.ElapsedEventArgs e)
{
MessageBox.Show(DateTime.Now.ToString());
}
Here is working console example:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("App started");
var timer = new System.Timers.Timer(1800);
timer.Start();
timer.Elapsed += timerHandler;
Console.ReadLine();
}
private static void timerHandler(object sender, System.Timers.ElapsedEventArgs e)
{
Messenger(DateTime.UtcNow.ToString());
}
private static void Messenger(string time)
{
Console.WriteLine(time);
}
}
in visual studios c# windows form application, I have a timer which want it to stop after a movement but not straight away can you put in a 5 second delay in timer.stop(); if possible if not something similar.
private void timer1_Tick(object sender, EventArgs e)
{
pictureBox1.Top -= 1;
timer1.Stop();
}
You could use a counter to specify when to stop the timer: Initialize the counter with, say, 100, if your timer delay is 50ms and you want a "delay" of 5s. Then use
private void timer1_Tick(object sender, EventArgs e)
{
pictureBox1.Top -= 1;
counter--;
if (counter==0)
timer1.Stop();
}
You can use another timer-class: System.Timers.Timer
Initialize that one on 5 seconds, handle the Elapsed event, in wich you stop your first timer.
Be sure to make it thread safe!
Thread-Safe Calls to a Windows Forms Control
I did it like this, i dont think using a timer is the best option here but to satisfy your needs.
Thread runner;
private void button1_Click(object sender, EventArgs e)
{
timer1.Start();
timer1.Interval = 1000;
textBox1.Text = "Amazing"; // initial process
}
private void timer1_Tick(object sender, EventArgs e)
{
if (runner != null && runner.IsAlive)
return;
runner = new Thread(new ThreadStart(() =>
{
// run your process here
Thread.Sleep(5000);
StopRunner();
}));
runner.Start();
}
private void StopRunner()
{
timer1.Stop();
// post process here
}
What it does is it processes your actual request then it'll exit the timer after. I checked if the thread is alive so it wont reprocess it.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How To Start And Stop A Continuously Running Background Worker Using A Button
I have 2 buttons the first one it's name "Continuous" .. the second one "Stop"
I want to call a method when press the continuous button :
private void continuous_Click(object sender ,EvantArgs e)
{
// continuous taking pictures ...
}
my question is : how can I stop the execution by pressing the stop button ??
I've written a code to take a picture and I've succeeded to take pictures ...
now I want the camera to take continuous snapshots ... but if I press stop button the camera should stop taking pictures ...
I've used BackGroundWorker but the code does not work !!!
this is the code :
private void ContinousSnaps_Click(object sender, EventArgs e)
{
Contiguous.DoWork += Contiguous_DoWork;
Contiguous.RunWorkerCompleted += Contiguous_RunWorkerCompleted;
Contiguous.RunWorkerAsync();
}
private void Contiguous_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; ; i++) TakeSnapShotCommand();
}
private void Contiguous_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
MessageBox.Show("complete");
}
//------------------------------------------------------------------//
private void Stop_Click(object sender, EventArgs e)
{
Contiguous.CancelAsync();
}
//--------------------------------------------------------------------//
how can I achieve the result that I want ?!
Try and see if this is going to work:
In your _DoWork event:
private void Contiguous_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; ; i++)
{
if (Contiguous.CancellationPending)
{
e.Cancel = true;
return;
}
TakeSnapShotCommand();
}
}
And in the Stop_Click to the following:
private void Stop_Click(object sender, EventArgs e)
{
if (Contiguous.WorkerSupportsCancellation)
Contiguous.CancelAsync();
}
Also make sure you allow cancellation (and if you want to take my advice here - move these event registrations in a the form load, so they will be executed once, not every time the button is clicked - leave just the Continuous.RunWorkerAsync()):
// your form load <---
private void Form1_Load(object sender, EventArgs e)
{
Contiguous.DoWork += Contiguous_DoWork;
Contiguous.RunWorkerCompleted += Contiguous_RunWorkerCompleted;
Contiguous.WorkerSupportsCancellation = true; // allowing cancellation
}
private void ContinousSnaps_Click(object sender, EventArgs e)
{
// not a bad idea if you disable the button here at this point
Contiguous.RunWorkerAsync();
}
Currently I'm moving from java to c# and I'm full of crazy questions.
I'm trying new things on a windows form application and now,I would like to create a loop wich is executing a code every 1 minute,the problem is that I have no idea where to put this code.
For example,the form structure is like:
using System;
namespace Tray_Icon
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
notifyIcon1.ShowBalloonTip(5000);
}
private void notifyIcon1_BalloonTipClicked(object sender, EventArgs e)
{
label1.Text = "Baloon clicked!";
}
private void notifyIcon1_BalloonTipClosed(object sender, EventArgs e)
{
label1.Text = "baloon closed!";
}
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
}
private void option1ToolStripMenuItem_Click(object sender, EventArgs e)
{
//some code here
}
private void option2ToolStripMenuItem_Click(object sender, EventArgs e)
{
//some code here
}
private void option3ToolStripMenuItem_Click(object sender, EventArgs e)
{
label1.Text = "Option 3 clicked!";
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
option1ToolStripMenuItem_Click(this, null);
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnWrite_Click(object sender, EventArgs e)
{
//code here
}
}
}
Where should I put the loop code? :(
Thanks in advance for ANY replay!!!
Add a Timer to your form:
set its Interval property to 60000 (one minute in milliseconds) and Enabled to True:
and attach an event handler to the Timer.Tick event, e.g. by double-clicking the timer in the Forms designer:
private void timer1_Tick(object sender, EventArgs e)
{
// do something here. It will be executed every 60 seconds
}
You would have to add a timer, and set the interval to 1000 miliseconds, and in the OnTick event you add the code with your loop
Timer tmr = null;
private void StartTimer()
{
tmr = new Timer();
tmr.Interval = 1000;
tmr.Tick += new EventHandler<EventArgs>(tmr_Tick);
tmr.Enabled = true;
}
void tmr_Tick(object sender, EventArgs e)
{
// Code with your loop here
}
You can't put any loop code in here.
In your designer look for the Timer control. When you have that, configure it to run every minute and place your code in the Timer_Tick event.
Or create a timer manually in code and respond to the event :) But for starters, doing it by the designer is easier!
Drag a Timer component on the Form and doubleclick it. There you go with the code.
The Timer component runs in the main thread so you can modify UI components without worrying.
Alternatively You could create a System.Timers.Timer, which has it's own thread and has some advantages, but possible caveats when modifying UI components. See http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx
Try to use Background Worker and put the code in the backgroundWorker.DoWork or use a Timer
Use System.Timers.Timer:
System.Timers.Timer aTimer;
{
aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 60000;
aTimer.Enabled = true;
}
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
}
for using Timer see this tutorial: C# Timer
How you do it in Java platform?
I think Java should be the same with .net.
In fact, a form program is just normal program which contains a event dispatcher. The event dispatcher listen to the UI events and dispatch them to the event handlers. I think all the UI mode should like this, no matter Java or .net platform.
So generally speaking, you have 2 options:
Start the loop at beginning. In this case, you should insert your
code in the constructor of the Form.
Start the loop when user
click the button. In this case, you should insert your code in the
event handler function.
Yes, as others mentioned, you should use the timer. But this should after you know where your code should locate. You also can use a endless loop with a sleep call. But timer is a better solution.
Idea of timer is more better. But If you want to use threads. Then Follow this
Let me assume that You want to do it right from the start of program
You can write in body of function (event in fact) named Form1_Load as
Your actual code is just within while loop other code only to guide
I can guide if you don't know the use of threads in C#
bool button2Clicked = false;
private void Form1_Load(object sender, EventArgs e)
{
// A good Way to call Thread
System.Threading.Thread t1 = new System.Threading.Thread(delegate()
{
while (!button2Clicked)
{
// Do Any Stuff;
System.Threading.Thread.Sleep(60000); //60000 Millieconds=1M
}
});
t1.IsBackground = true; // With above statement Thread Will automatically
// be Aborted on Application Exit
t1.Start();
}