Re: Visual C# General Using multimedia timer with managed C++
nobugz
Here's a sample application that uses timeSetEvent(). A couple of problem I ran into when developing it. The IDE debugger can't handle the callback, avoid breakpoints in that code. I had trouble shutting down the timer with timeKillEvent(); calling Invoke() caused a strange ObjectDisposedException and asking for a synchronous kill just hung the program. Please post back any improvements you make. Good luck!
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsApplication1 {
public partial class Form1 : Form {
private int mTimerId;
private TimerEventHandler mHandler; // NOTE: declare at class scope so garbage collector doesn't release it!!!
private int mTestTick;
private DateTime mTestStart;
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
timeBeginPeriod(1);
mHandler = new TimerEventHandler(TimerCallback);
mTimerId = timeSetEvent(1, 0, mHandler, IntPtr.Zero, EVENT_TYPE);
mTestStart = DateTime.Now;
mTestTick = 0;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
int err = timeKillEvent(mTimerId);
timeEndPeriod(1);
mTimerId = 0;
System.Threading.Thread.Sleep(1000); // Avoid ObjectDisposed exception !
}
// Testing:
private delegate void TestEventHandler(int tick, TimeSpan span);
private void TimerCallback(int id, int msg, IntPtr user, int dw1, int dw2) {
mTestTick += 1;
if ((mTestTick % 200) == 0 && mTimerId != 0)
this.BeginInvoke(new TestEventHandler(ShowTick), mTestTick, DateTime.Now - mTestStart);
}
private void ShowTick(int msec, TimeSpan span) {
label1.Text = msec.ToString();
label2.Text = span.TotalMilliseconds.ToString();
}
// P/Invoke declarations
private delegate void TimerEventHandler(int id, int msg, IntPtr user, int dw1, int dw2);
private const int TIME_PERIODIC = 1;
private const int EVENT_TYPE = TIME_PERIODIC;// + 0x100; // TIME_KILL_SYNCHRONOUS causes a hang !
[DllImport("winmm.dll")]
private static extern int timeSetEvent(int delay, int resolution, TimerEventHandler handler, IntPtr user, int eventType);
[DllImport("winmm.dll")]
private static extern int timeKillEvent(int id);
[DllImport("winmm.dll")]
private static extern int timeBeginPeriod(int msec);
[DllImport("winmm.dll")]
private static extern int timeEndPeriod(int msec);
}
}