My Timer won't tick c# - c#

My timer won't tick, I've tried with printing to check if the timer is started, it starts but it never ticks.
Here's the code:
public Form1()
{
InitializeComponent();
this.DoubleBuffered = true;
timer = new Timer();
timer.Enabled = true;
timer.Interval = 50;
timer.Tick += new EventHandler(timer_Tick);
//Console.WriteLine("STARTING TIMER");
timer.Start();
NewFile();
}
private void timer_Tick(object sender, EventArgs e)
{
MessageBox.Show("TIMER TICKS");
doc.MoveBalls(leftX, topY, width, height);
doc.CheckCollision();
Invalidate(true);
Console.WriteLine("Moving2");
}

Apart from the answers given above, you may also use a thread of Timer which takes callback and a state object to keep your working thread safe like below
After you include the library before your namespace
using System.Threading;
// your namespace
private readonly TimeSpan _updateInterval = TimeSpan.FromSeconds(10);
private Timer _timer = new Timer(CallBakFunction, null, _updateInterval, _updateInterval);
private void CallBakFunction(object state)
{
}
In your case, this can be done as follows:
private readonly TimeSpan _updateInterval = TimeSpan.FromSeconds(10);
private Timer _timer ;
public Form1()
{
InitializeComponent();
this.DoubleBuffered = true;
_timer = new Timer(timer_Tick, null, _updateInterval, _updateInterval);
NewFile();
}
private void timer_Tick(object state)
{
MessageBox.Show("TIMER TICKS");
doc.MoveBalls(leftX, topY, width, height);
doc.CheckCollision();
Invalidate(true);
Console.WriteLine("Moving2");
}
I have updated a final result video for your assistance please view this:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private readonly TimeSpan _updateInterval = TimeSpan.FromSeconds(1);
private System.Threading.Timer _timer;
public Form1()
{
InitializeComponent(); this.DoubleBuffered = true;
_timer = new System.Threading.Timer(timer_Tick, null, _updateInterval, _updateInterval);
NewFile();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void NewFile() { }
private void timer_Tick(object state)
{
MessageBox.Show("TIMER TICKS");
//doc.MoveBalls(leftX, topY, width, height);
//doc.CheckCollision();
//Invalidate(true);
Console.WriteLine("Moving2");
}
}
}

You enabled the timer before you attach the OnTick event. Setting Enabled to true is basically the same as timer.Start(). Remove the Enabled assignment, or replace the Start() call with it.

Use System.Windows.Forms.Timer to work with winform
public Form1()
{
InitializeComponent();
this.DoubleBuffered = true;
System.Windows.Forms.Timer timer = new Timer();
timer.Enabled = true;
timer.Interval = 50;
timer.Tick += new EventHandler(timer_Tick);
//Console.WriteLine("STARTING TIMER");
timer.Start();
}

Related

How do I make a winform minimize animation

How can I add an animation to Form's Minimize?
Here's an example: https://i.gyazo.com/fddb5bf0ce748ae69320ae08e1986ac3.mp4
I am using Winforms C#
EDITED:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TestMinimize
{
public partial class Form1 : Form
{
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
System.Windows.Forms.Timer t1 = new System.Windows.Forms.Timer();
bool Minimized;
public Form1()
{
InitializeComponent();
t.Interval = 2; // specify interval time as you want
t.Tick += new EventHandler(timer_Tick);
this.SizeChanged += new EventHandler(this_SizeChanged);
t1.Interval = 1;
t1.Tick += new EventHandler(timer1_Tick);
t1.Start();
}
private void this_SizeChanged(object source, EventArgs e)
{
if (this.WindowState == FormWindowState.Normal)
{
Minimized = false;
}
}
private void timer_Tick(object source, EventArgs e)
{
this.Height = this.Height-8;
if (this.Height == 39)
{
t.Stop();
t.Enabled = false;
this.WindowState = FormWindowState.Minimized;
Minimized = true;
}
}
private void timer1_Tick(object source, EventArgs e)
{
if(Minimized==false && t.Enabled == false)
{
this.Height = 221;
}
}
private void button1_Click(object sender, EventArgs e)
{
t.Start();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}

Perform an action when a timer elapses [duplicate]

This question already has an answer here:
how to display a message box when timer elapses in c#
(1 answer)
Closed 8 years ago.
I want to provide a beep sound to indicate that my timer is elapsed. Where would I put the code such that it happens when my timer has expired?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
Timer aTimer = new Timer();
aTimer.Interval = 1000;
// Hook up the Elapsed event for the timer.
aTimer.Enabled = true;
aTimer.tick += OnTimedEvent;
}
private void OnTimedEvent(object sender, EventArgs e)
{
MessageBox.Show("process");
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Media;
namespace delete
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer1.Enabled = true;
timer1.Interval = 1000;
}
private void timer1_Tick(object sender, EventArgs e)
{
SoundPlayer sp = new SoundPlayer();
sp.Play();
}
}
}
don't forget to add using System.Media;

Elapsed event for the time not working, c#

I am using a timer to output text to textbox every 2 seconds. but it seems that it doesnt work. any idea what is wrong. here is my code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static System.Timers.Timer aTimer;
public void BtnGenData_Click(object sender, EventArgs e)
{
aTimer = new System.Timers.Timer(10000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 2 seconds (2000 milliseconds).
aTimer.Interval = 2000;
aTimer.Enabled = true;
}
public static void OnTimedEvent(object source, ElapsedEventArgs e)
{
string GenData = "Welcome";
Form1 frm1 = new Form1();
frm1.TboxData.AppendText(GenData.ToString());
}
}
Actually i dont see any output coming.
Although this is not straightly connected with the problem you have in your code, but...
From MSDN System.Timers.Timer:
The server-based Timer is designed for use with worker threads in a
multithreaded environment.
In Windows Forms you can use System.WindowsForms.Timer:
System.Windows.Forms.Timer timer;
public Form1()
{
InitializeComponent();
timer = new Timer();
timer.Interval = 1000;
timer.Tick += new EventHandler(timer_Tick);
}
public void BtnGenData_Click(object sender, EventArgs e)
{
BtnGenData.Enabled = false;
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
timer.Stop();
BtnGenData.Enabled = true;
//do what you need
}
As for your code, why make the timer static? Try to use this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public System.Timers.Timer aTimer;
public void BtnGenData_Click(object sender, EventArgs e)
{
aTimer = new System.Timers.Timer(10000);
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 2000;
aTimer.Enabled = true;
}
public void OnTimedEvent(object source, ElapsedEventArgs e)
{
this.TboxData.AppendText("Welcome");
}
}
Also you should take into consideration, what could happen if you pressed the button twice...
The problem is in this method:
public static void OnTimedEvent(object source, ElapsedEventArgs e)
{
string GenData = "Welcome";
Form1 frm1 = new Form1();
frm1.TboxData.AppendText(GenData.ToString());
}
By calling new Form1(); you create a new form. This form is created as hidden, you change the text, but it is not displayed and at the end of this method it is garbage collected. What you want is to reuse your existing one. Completely remove this line and use your existing form. By default the name should be form1
public static void OnTimedEvent(object source, ElapsedEventArgs e)
{
string GenData = "Welcome";
form1.TboxData.AppendText(GenData.ToString());
}

change timer interval in other thread

I'd like to change a timer interval in another thread:
class Context : ApplicationContext {
private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
public Context() {
timer.Interval = 1;
timer.Tick += timer_Tick;
timer.Start();
Thread t = new Thread(ChangeTimerTest);
t.Start();
}
private void ChangeTimerTest() {
System.Diagnostics.Debug.WriteLine("thread run");
timer.Interval = 2;
}
private void timer_Tick(object sender,EventArgs args) {
System.Diagnostics.Debug.WriteLine(System.DateTime.Now.ToLongTimeString());
}
}
But the timer stops when I change the interval in the new thread. No errors, timer just stops.
Why is this happening and how can I fix it?
thx
Try this, I tried it and it works, I only changed new interval from 2 to 2000ms so you can see the difference in the Output.
You have to change interval in a thread safe manner your interval because the timer is in UI thread context. In these cases it is recommended to use delegates.
private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
public void Context() {
timer.Interval = 1;
timer.Tick += timer_Tick;
timer.Start();
Thread t = new Thread(ChangeTimerTest);
t.Start();
}
delegate void intervalChanger();
void ChangeInterval()
{
timer.Interval = 2000;
}
void IntervalChange()
{
this.Invoke(new intervalChanger(ChangeInterval));
}
private void ChangeTimerTest() {
System.Diagnostics.Debug.WriteLine("thread run");
IntervalChange();
}
private void timer_Tick(object sender,EventArgs args) {
System.Diagnostics.Debug.WriteLine(System.DateTime.Now.ToLongTimeString());
}
In addition to my previous answer, since you are not using Forms, try to change your System.Windows.Forms.Timer to System.Timers.Timer. Note that it has Elapsed Event, not Tick. The following is the code:
System.Timers.Timer timer = new System.Timers.Timer();
public Context() {
timer.Interval = 1;
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Start();
Thread t = new Thread(ChangeTimerTest);
t.Start();
}
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
System.Diagnostics.Debug.WriteLine(System.DateTime.Now.ToLongTimeString());
}
private void ChangeTimerTest() {
System.Diagnostics.Debug.WriteLine("thread run");
timer.Interval = 2000;
}
Hope this will finally help!

Timer Tick after FormClosing?

Is there any chance that timer_Tick could be called after myForm_FormClosing
in the code below.
If there is a chance: Is it sufficient to call timer.Stop() within myForm_FormClosing in order to avoid that timer_Tick gets called after myForm_FormClosing?
using System;
using System.Windows.Forms;
using System.ComponentModel;
namespace Test
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyForm());
}
}
class MyForm : Form
{
private IContainer components;
private Timer timer;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
public MyForm()
{
components = new Container();
timer = new Timer(components);
timer.Interval = 50;
timer.Tick += timer_Tick;
timer.Enabled = true;
FormClosing += myForm_FormClosing;
}
private void timer_Tick(object sender, EventArgs e)
{
}
private void myForm_FormClosing(object sender, FormClosingEventArgs e)
{
}
}
}
Update:
After receving a few hints (thanks for helping) I basically have chosen the following code to achive what I want.
Please not that timer1_Tick could still be called after myForm_FormClosing was called!
This solution just introduces a flag (i called it doWork) which stops the code within timer1_Tick to be executed after myForm_FormClosing was called.
using System;
using System.Windows.Forms;
using System.ComponentModel;
namespace Test
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyForm());
}
}
class MyForm : Form
{
private IContainer components;
private Timer timer;
private bool doWork = true;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
public MyForm()
{
components = new Container();
timer = new Timer(components);
timer.Interval = 50;
timer.Tick += timer_Tick;
timer.Enabled = true;
FormClosing += myForm_FormClosing;
}
private void timer_Tick(object sender, EventArgs e)
{
if (doWork)
{
//do the work
}
}
private void myForm_FormClosing(object sender, FormClosingEventArgs e)
{
doWork = false;
}
}
}
Yes it is possible. According to the docs ...
Occurs before the form is closed.
When a form is closed, it is disposed, releasing all resources
associated with the form.
The timer will not be disposed until after the FormClosing event. Here is a very contrived example of how it can happen. You will see that you hit the debugger breakpoint on the Timer tick after FormClosing has been called.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private System.Windows.Forms.Timer _time = new System.Windows.Forms.Timer();
private Task _t1 = null;
private Task _t2 = null;
private bool _closingFlag = false;
public Form1()
{
InitializeComponent();
_time.Interval = 50;
_time.Tick += (s, e) => {
textBox1.Text = DateTime.Now.ToString();
if (_closingFlag) Debugger.Break();
};
_time.Start();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
_closingFlag = true;
_t1 = Task.Factory.StartNew(() => { Thread.Sleep(1000); });
_t2 = Task.Factory.StartNew(() => { Thread.Sleep(1000); });
Task.WaitAll(_t1, _t2);
}
}
}
If you use a the timer System.Windows.Forms.Timer the UI thread must be idle to process a tick from the timer, so from my understanding that's is not possible.
Could happen if you use a timer with its own thread, as a System.Timers.Timer. In this case we could avoid what you mention by implementing something like this:
class MyForm : Form
{
private System.Timers.Timer timer;
private Object justForLocking = new Object();
private Boolean safeToProceed = true;
[...]
public MyForm()
{
components = new Container();
timer = new System.Timers.Timer();
timer.Interval = 50;
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Start();
FormClosing += myForm_FormClosing;
}
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
// In case that this code is being executed after
// the method myForm_FormClosing has adquired the
// exclusive lock over our dummy resource,
// the timer thread will wait until the resource if released.
// Once is released, our control flag will be set to false
// and the timer should just return and never execute again.
lock(justForLocking)
{
if (safeToProceed)
{
// Do whatever you want to do at this point
}
}
}
private void myForm_FormClosing(object sender, FormClosingEventArgs e)
{
lock(justForLocking)
{
safeToProceed = false;
}
timer.Stop();
// Do something else
}
[...]
}
This other SO question has relevant information.
EDIT: the code above is only valid if a System.Timers.Timer is used instead of System.Windows.Forms.Timer
I dont believe so but it would be best anyways to call timer.stop() regardless. if you were needing it to though you should create the timer object in program.cs

Categories