我的计时器不会打勾,我已尝试打印以检查计时器是否已启动,它会启动,但它永远不会打勾。 这是代码:
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");
}
答案 0 :(得分:1)
您在附加QByteArray
事件之前启用了计时器。将OnTick
设置为true与Enabled
基本相同。删除已启用的分配,或用它替换Start()调用。
答案 1 :(得分:1)
除了上面给出的答案之外,您还可以使用Timer的一个线程来获取回调和一个状态对象来保持您的工作线程安全,如下所示
在命名空间之前包含库
using System.Threading;
//你的命名空间
private readonly TimeSpan _updateInterval = TimeSpan.FromSeconds(10);
private Timer _timer = new Timer(CallBakFunction, null, _updateInterval, _updateInterval);
private void CallBakFunction(object state)
{
}
在您的情况下,可以按照以下方式完成:
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");
}
我已更新final result video以获取您的帮助,请查看以下内容:
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");
}
}
}
答案 2 :(得分:0)
使用System.Windows.Forms.Timer
使用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();
}