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)
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. }
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 .
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()
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With