using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using CtimerwCs;
using System.Runtime.InteropServices;

namespace IntervalCallback
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class IntervalCallback : System.Windows.Forms.Form
	{
		Ctimerw timerw = new Ctimerw();

		public uint				interval_count;
		public short    		TimerId;
        static public GCHandle  gCh;
        static public PTM_INTERVAL_CALLBACK pdelegate_func;
        static public IntPtr    pfunc;

		private System.Windows.Forms.Button Button_Exit;
		private System.Windows.Forms.Button Button_TimExit;
		private System.Windows.Forms.Button Button_TimStopTimer;
		private System.Windows.Forms.Button Button_TimStartTimer;
		private System.Windows.Forms.Button Button_TimInit;
		private System.Windows.Forms.GroupBox groupBox4;
		private System.Windows.Forms.TextBox Text_Ret;
		private System.Windows.Forms.GroupBox groupBox3;
		private System.Windows.Forms.GroupBox groupBox2;
		private System.Windows.Forms.TextBox Text_Interval;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.GroupBox groupBox1;
		private System.Windows.Forms.Label Label_ProductName;
		private System.Windows.Forms.Label label4;
		private System.Windows.Forms.TextBox Text_DeviceName;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.Label Label_CallbackCount;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public IntervalCallback()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.Button_Exit = new System.Windows.Forms.Button();
			this.Button_TimExit = new System.Windows.Forms.Button();
			this.Button_TimStopTimer = new System.Windows.Forms.Button();
			this.Button_TimStartTimer = new System.Windows.Forms.Button();
			this.Button_TimInit = new System.Windows.Forms.Button();
			this.groupBox4 = new System.Windows.Forms.GroupBox();
			this.Text_Ret = new System.Windows.Forms.TextBox();
			this.groupBox3 = new System.Windows.Forms.GroupBox();
			this.Label_CallbackCount = new System.Windows.Forms.Label();
			this.groupBox2 = new System.Windows.Forms.GroupBox();
			this.Text_Interval = new System.Windows.Forms.TextBox();
			this.label2 = new System.Windows.Forms.Label();
			this.groupBox1 = new System.Windows.Forms.GroupBox();
			this.Label_ProductName = new System.Windows.Forms.Label();
			this.label4 = new System.Windows.Forms.Label();
			this.Text_DeviceName = new System.Windows.Forms.TextBox();
			this.label3 = new System.Windows.Forms.Label();
			this.groupBox4.SuspendLayout();
			this.groupBox3.SuspendLayout();
			this.groupBox2.SuspendLayout();
			this.groupBox1.SuspendLayout();
			this.SuspendLayout();
			// 
			// Button_Exit
			// 
			this.Button_Exit.Location = new System.Drawing.Point(264, 144);
			this.Button_Exit.Name = "Button_Exit";
			this.Button_Exit.Size = new System.Drawing.Size(92, 24);
			this.Button_Exit.TabIndex = 26;
			this.Button_Exit.Text = "Exit";
			this.Button_Exit.Click += new System.EventHandler(this.Button_Exit_Click);
			// 
			// Button_TimExit
			// 
			this.Button_TimExit.Location = new System.Drawing.Point(264, 112);
			this.Button_TimExit.Name = "Button_TimExit";
			this.Button_TimExit.Size = new System.Drawing.Size(92, 24);
			this.Button_TimExit.TabIndex = 25;
			this.Button_TimExit.Text = "TimExit";
			this.Button_TimExit.Click += new System.EventHandler(this.Button_TimExit_Click);
			// 
			// Button_TimStopTimer
			// 
			this.Button_TimStopTimer.Location = new System.Drawing.Point(264, 80);
			this.Button_TimStopTimer.Name = "Button_TimStopTimer";
			this.Button_TimStopTimer.Size = new System.Drawing.Size(92, 25);
			this.Button_TimStopTimer.TabIndex = 24;
			this.Button_TimStopTimer.Text = "TimStopTimer";
			this.Button_TimStopTimer.Click += new System.EventHandler(this.Button_TimStopTimer_Click);
			// 
			// Button_TimStartTimer
			// 
			this.Button_TimStartTimer.Location = new System.Drawing.Point(264, 40);
			this.Button_TimStartTimer.Name = "Button_TimStartTimer";
			this.Button_TimStartTimer.Size = new System.Drawing.Size(92, 25);
			this.Button_TimStartTimer.TabIndex = 23;
			this.Button_TimStartTimer.Text = "TimStartTimer";
			this.Button_TimStartTimer.Click += new System.EventHandler(this.Button_TimStartTimer_Click);
			// 
			// Button_TimInit
			// 
			this.Button_TimInit.Location = new System.Drawing.Point(264, 8);
			this.Button_TimInit.Name = "Button_TimInit";
			this.Button_TimInit.Size = new System.Drawing.Size(92, 25);
			this.Button_TimInit.TabIndex = 22;
			this.Button_TimInit.Text = "TimInit";
			this.Button_TimInit.Click += new System.EventHandler(this.Button_TimInit_Click);
			// 
			// groupBox4
			// 
			this.groupBox4.Controls.AddRange(new System.Windows.Forms.Control[] {
																					this.Text_Ret});
			this.groupBox4.Location = new System.Drawing.Point(8, 173);
			this.groupBox4.Name = "groupBox4";
			this.groupBox4.Size = new System.Drawing.Size(352, 54);
			this.groupBox4.TabIndex = 21;
			this.groupBox4.TabStop = false;
			this.groupBox4.Text = "Ret";
			// 
			// Text_Ret
			// 
			this.Text_Ret.Location = new System.Drawing.Point(8, 19);
			this.Text_Ret.Name = "Text_Ret";
			this.Text_Ret.Size = new System.Drawing.Size(312, 20);
			this.Text_Ret.TabIndex = 0;
			this.Text_Ret.Text = "";
			// 
			// groupBox3
			// 
			this.groupBox3.Controls.AddRange(new System.Windows.Forms.Control[] {
																					this.Label_CallbackCount});
			this.groupBox3.Location = new System.Drawing.Point(8, 128);
			this.groupBox3.Name = "groupBox3";
			this.groupBox3.Size = new System.Drawing.Size(248, 43);
			this.groupBox3.TabIndex = 20;
			this.groupBox3.TabStop = false;
			this.groupBox3.Text = "Count";
			// 
			// Label_CallbackCount
			// 
			this.Label_CallbackCount.Location = new System.Drawing.Point(16, 20);
			this.Label_CallbackCount.Name = "Label_CallbackCount";
			this.Label_CallbackCount.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
			this.Label_CallbackCount.Size = new System.Drawing.Size(140, 11);
			this.Label_CallbackCount.TabIndex = 0;
			this.Label_CallbackCount.Text = "0";
			// 
			// groupBox2
			// 
			this.groupBox2.Controls.AddRange(new System.Windows.Forms.Control[] {
																					this.Text_Interval,
																					this.label2});
			this.groupBox2.Location = new System.Drawing.Point(8, 72);
			this.groupBox2.Name = "groupBox2";
			this.groupBox2.Size = new System.Drawing.Size(248, 50);
			this.groupBox2.TabIndex = 19;
			this.groupBox2.TabStop = false;
			this.groupBox2.Text = "Interval";
			// 
			// Text_Interval
			// 
			this.Text_Interval.Location = new System.Drawing.Point(16, 19);
			this.Text_Interval.Name = "Text_Interval";
			this.Text_Interval.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
			this.Text_Interval.Size = new System.Drawing.Size(144, 20);
			this.Text_Interval.TabIndex = 1;
			this.Text_Interval.Text = "";
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(168, 23);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(32, 19);
			this.label2.TabIndex = 0;
			this.label2.Text = "[us]";
			// 
			// groupBox1
			// 
			this.groupBox1.Controls.AddRange(new System.Windows.Forms.Control[] {
																					this.Label_ProductName,
																					this.label4,
																					this.Text_DeviceName,
																					this.label3});
			this.groupBox1.Location = new System.Drawing.Point(8, 8);
			this.groupBox1.Name = "groupBox1";
			this.groupBox1.Size = new System.Drawing.Size(248, 65);
			this.groupBox1.TabIndex = 18;
			this.groupBox1.TabStop = false;
			this.groupBox1.Text = "Initialization";
			// 
			// Label_ProductName
			// 
			this.Label_ProductName.Location = new System.Drawing.Point(91, 43);
			this.Label_ProductName.Name = "Label_ProductName";
			this.Label_ProductName.Size = new System.Drawing.Size(149, 13);
			this.Label_ProductName.TabIndex = 3;
			this.Label_ProductName.Text = "Not Initialization";
			// 
			// label4
			// 
			this.label4.Location = new System.Drawing.Point(8, 43);
			this.label4.Name = "label4";
			this.label4.Size = new System.Drawing.Size(83, 14);
			this.label4.TabIndex = 2;
			this.label4.Text = "Product Name:";
			// 
			// Text_DeviceName
			// 
			this.Text_DeviceName.Location = new System.Drawing.Point(92, 15);
			this.Text_DeviceName.Name = "Text_DeviceName";
			this.Text_DeviceName.Size = new System.Drawing.Size(117, 20);
			this.Text_DeviceName.TabIndex = 1;
			this.Text_DeviceName.Text = "";
			// 
			// label3
			// 
			this.label3.Location = new System.Drawing.Point(8, 19);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(80, 18);
			this.label3.TabIndex = 0;
			this.label3.Text = "Device Name:";
			// 
			// IntervalCallback
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(362, 230);
			this.Controls.AddRange(new System.Windows.Forms.Control[] {
																		  this.Button_Exit,
																		  this.Button_TimExit,
																		  this.Button_TimStopTimer,
																		  this.Button_TimStartTimer,
																		  this.Button_TimInit,
																		  this.groupBox4,
																		  this.groupBox3,
																		  this.groupBox2,
																		  this.groupBox1});
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
			this.MaximizeBox = false;
			this.MinimizeBox = false;
			this.Name = "IntervalCallback";
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "Interval Timer (Callback Edition)";
			this.Load += new System.EventHandler(this.IntervalCallback_Load);
			this.groupBox4.ResumeLayout(false);
			this.groupBox3.ResumeLayout(false);
			this.groupBox2.ResumeLayout(false);
			this.groupBox1.ResumeLayout(false);
			this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new IntervalCallback());
		}

		unsafe private void IntervalCallback_Load(object sender, System.EventArgs e)
		{
			Text_Interval.Text = "1000";
			Button_TimStopTimer.Enabled = false;

            //-----------------------------------
            // Initialize the delegate for Interval Timer event processing
            //-----------------------------------
            pdelegate_func = new PTM_INTERVAL_CALLBACK(CallBackProc);
            //-----------------------------------
            // Do not release the delegate
            //-----------------------------------
            if (gCh.IsAllocated == false)
            {
                gCh = GCHandle.Alloc(pdelegate_func);
            }
		}

		//==============================================================================
		// TimInit
		//==============================================================================
		private void Button_TimInit_Click(object sender, System.EventArgs e)
		{
			string	DeviceName;
			string	ProductName;
			string	ErrorString;
			int		ret;

			//-----------------------------------
			// Get Device Name
			//-----------------------------------
			DeviceName = Text_DeviceName.Text;
			//-----------------------------------
			// Initialization
			//-----------------------------------
			ret = timerw.Init(ref DeviceName, out ProductName);
			//-----------------------------------
			// Error handle
			//-----------------------------------
			timerw.GetErrorString(ret, out ErrorString);
			Text_Ret.Text = "TimInit ret = " + System.Convert.ToString(ret) + " " + ErrorString;
			if (ret == (int)CtimerwConst.TIM_ERR_SUCCESS)
			{
				Text_DeviceName.Text = DeviceName;
				Label_ProductName.Text = ProductName;
			}
		}

		//==============================================================================
		// TimStartTimer
		//==============================================================================
		unsafe private void Button_TimStartTimer_Click(object sender, System.EventArgs e)
		{
			string	ErrorString;
			uint	Microseconds;
			int		ret;

			//-----------------------------------
			// Interval Count Initialization
			//-----------------------------------
			interval_count = 0;
			//-----------------------------------
			// Get the specified value of Interval
			//-----------------------------------
			Microseconds = System.Convert.ToUInt32(Text_Interval.Text);
			//-----------------------------------
			// Start Interval Timer 
			//-----------------------------------
			ret = timerw.StartTimer(out TimerId, Microseconds, this.Handle.ToInt32());
			//-----------------------------------
			// Error handle
			//-----------------------------------
			timerw.GetErrorString(ret, out ErrorString);
			Text_Ret.Text = "TimStartTimer ret = " + System.Convert.ToString(ret) + " " + ErrorString;
			if (ret != (int)CtimerwConst.TIM_ERR_SUCCESS)
			{
				return;
			}
			//-----------------------------------
            // Get the fixed pointer of the delegate for for Interval Timer event processing
			//-----------------------------------
            pfunc = Marshal.GetFunctionPointerForDelegate(pdelegate_func);
            //-----------------------------------
            // Interval Timer Callback registration
            //-----------------------------------
			fixed (short *Temp = &TimerId)
                ret = timerw.TimerCallBackProc(TimerId, pfunc, Temp);
			//-----------------------------------
			// Error handle
			//-----------------------------------
			timerw.GetErrorString(ret, out ErrorString);
			Text_Ret.Text = "TimTimerCallBackProc ret = " + System.Convert.ToString(ret) + " " + ErrorString;
			if (ret == (int)CtimerwConst.TIM_ERR_SUCCESS)
			{
				//-----------------------------------
				// Enable the TimStopTimer button 
				//-----------------------------------
				Button_TimStopTimer.Enabled = true;
				//-----------------------------------
				// Disable the TimStartTimer button
				//-----------------------------------
				Button_TimStartTimer.Enabled = false;
			}		
		}

		//==============================================================================
		// TimStopTimer
		//==============================================================================
		private void Button_TimStopTimer_Click(object sender, System.EventArgs e)
		{
			string	ErrorString;
			int		ret;

			//-----------------------------------
			// Stop Interval Timer 
			//-----------------------------------
			ret = timerw.StopTimer(TimerId);
			//-----------------------------------
			// Error handle
			//-----------------------------------
			timerw.GetErrorString(ret, out ErrorString);
			Text_Ret.Text = "TimStopTimer ret = " + System.Convert.ToString(ret) + " " + ErrorString;
			if (ret == (int)CtimerwConst.TIM_ERR_SUCCESS)
			{
				//-----------------------------------
				// Disable the TimStopTimer button 
				//-----------------------------------
				Button_TimStopTimer.Enabled = false;
				//-----------------------------------
				// Enable the TimStartTimer button 
				//-----------------------------------
				Button_TimStartTimer.Enabled = true;
			}
		}

		//==============================================================================
		// TimExit
		//==============================================================================
		private void Button_TimExit_Click(object sender, System.EventArgs e)
		{
			string	ErrorString;
			int		ret;

			//-----------------------------------
			// Exit handle
			//-----------------------------------
			ret = timerw.Exit();
			//-----------------------------------
			// Error handle
			//-----------------------------------
			timerw.GetErrorString(ret, out ErrorString);
			Text_Ret.Text = "TimExit ret = " + System.Convert.ToString(ret) + " " + ErrorString;
			//-----------------------------------
			// Disable the TimStopTimer button 
			//-----------------------------------
			Button_TimStopTimer.Enabled = false;
			//-----------------------------------
			// Enable the TimStartTimer button 
			//-----------------------------------
			Button_TimStartTimer.Enabled = true;
		}

		//==============================================================================
		// Exit
		//==============================================================================
		private void Button_Exit_Click(object sender, System.EventArgs e)
		{
            //-----------------------------------
            // Release the garbage collection handle of the delegate for Interval Timer event processing
            //-----------------------------------
            if (gCh.IsAllocated == true)
            {
                gCh.Free();
            }
			this.Close();
		}

		delegate void SetCountDelegate();
		//==============================================================================
		// Synchronous function for control operation
		//==============================================================================
		void SetCountText()
		{
			Label_CallbackCount.Text = System.Convert.ToString(interval_count);
		}

		//==============================================================================
        // Callback routine - Interval Timer event processing
		//==============================================================================
		unsafe public void CallBackProc(short TimerId, int wParam, int lParam, void *Param)
		{
			interval_count++;
            //-----------------------------------
            // Show the count value
            //-----------------------------------
			this.Invoke(new SetCountDelegate(SetCountText));
			return;
		}
	}
}
