How to make a fire timer only once

I am using C # 2.0 and working on Winforms. I have two applications (app1, app2). when starting application 1, it automatically calls application2. I have a timer in my application2, and in timer_tick I fire the buttonclick event. But I want this button to be pressed only once when the application is running.

The problem I ran into is some unknown reason why the timer starts more than once, although I do mytimer.Enable = false. Is there a way when I can make the timer not get called a second time. OR Is there a way I can make the click event of a button automatically without using timers.

Here is the code:

private void Form1_Activated(object sender, EventArgs e) { mytimer.Interval = 2000; mytimer.Enabled = true; mytimer.Tick += new System.EventHandler(timer1_Tick); } private void timer1_Tick(object sender, EventArgs e) { mytimer.Enabled = false; button1_Click(this, EventArgs.Empty); } private void button1_Click(object sender, EventArgs e) { } 
+4
source share
5 answers

I have not tested this yet (so be prepared to edit), but I suspect because you turned on the timer ( mytimer.Enabled = true; ) in the Form1_Activated event, and not when the form is initially loaded. Therefore, every time a form becomes active, it is reset. Turns on your timer.

EDIT: Ok, now I checked: if you really need a timer, move mytimer.Enabled to the form constructor.

+8
source
 public Form1 : Form() { InitializeComponent(); this.Load+= (o,e)=>{ this.button1.PerformClick();} } public void button1_Click(object sender, EventArgs e) { //do what you gotta do } 

No need to use a timer. Just a β€œclick” button when loading the form.

+4
source

This probably has nothing to do with it, but I would have turned on the timer after installing EventHandler. (This caused grief in the previous project, which later added more code between the two statements.)

+2
source

Set the timer AutoReset property to false : http://msdn.microsoft.com/en-us/library/system.timers.timer.autoreset.aspx

 private void Form1_Activated(object sender, EventArgs e) { mytimer.Interval = 2000; mytimer.AutoReset = false; mytimer.Tick += new System.EventHandler(timer1_Tick); mytimer.start(); } 

It also means that you do not need to cancel Enabled .

 private void timer1_Tick(object sender, EventArgs e) { mytimer.Enabled = false; button1_Click(this, EventArgs.Empty); } 
+2
source

You can try to remove the handler rather than disable the timer

 mytimer.Tick -= new System.EventHandler(timer1_Tick); 
+1
source

Source: https://habr.com/ru/post/1286093/


All Articles