Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute specified function every X seconds

Tags:

c#

.net

winforms

I have a Windows Forms application written in C#. The following function checks whenever printer is online or not:

public void isonline() {     PrinterSettings settings = new PrinterSettings();     if (CheckPrinter(settings.PrinterName) == "offline")     {         pictureBox1.Image = pictureBox1.ErrorImage;     } } 

and updates the image if the printer is offline. Now, how can I execute this function isonline() every 2 seconds so when I unplug the printer, the image displayed on the form (pictureBox1) turns into another one without relaunching the application or doing a manual check? (eg. by pressing "Refresh" button which runs the isonline() function)

like image 320
dan.dev.01 Avatar asked May 29 '11 17:05

dan.dev.01


People also ask

How do you call a function every second in C#?

You can use the solution below: static void Main(string[] args) { var timer = new Timer(Callback, null, 0, 2000); //Dispose the timer timer. Dispose(); } static void Callback(object? state) { //Your code here. }

How do you call a function every minute in C#?

It can be achieved by applying while loop and calling Thread. Sleep at the end of the loop. Make sure to include using System. Threading .


2 Answers

Use System.Windows.Forms.Timer.

private Timer timer1;  public void InitTimer() {     timer1 = new Timer();     timer1.Tick += new EventHandler(timer1_Tick);     timer1.Interval = 2000; // in miliseconds     timer1.Start(); }  private void timer1_Tick(object sender, EventArgs e) {     isonline(); } 

You can call InitTimer() in Form1_Load().

like image 176
Stecya Avatar answered Oct 13 '22 21:10

Stecya


The most beginner-friendly solution is:

Drag a Timer from the Toolbox, give it a Name, set your desired Interval, and set "Enabled" to True. Then double-click the Timer and Visual Studio (or whatever you are using) will write the following code for you:

private void wait_Tick(object sender, EventArgs e) {     refreshText(); // Add the method you want to call here. } 

No need to worry about pasting it into the wrong code block or something like that.

like image 44
philx_x Avatar answered Oct 13 '22 23:10

philx_x