Click here to Skip to main content
15,881,204 members
Articles / Multimedia / GDI+

C# Application to Create and Recognize Mouse Gestures (.NET)

Rate me:
Please Sign up or sign in to vote.
4.82/5 (39 votes)
17 Mar 2008CPOL5 min read 221.3K   8.1K   144  
This program can create and recognize mouse gestures.
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Xml;
using System.IO;

namespace MouseGesture
{
	#region MouseGestureMainForm class
	public class MouseGestureMainForm : System.Windows.Forms.Form
	{
		#region Static members
		public static string Version{get{return "1.8 beta";}}
		#endregion

		#region Visual Objects
		private System.ComponentModel.Container components = null;
		private System.Windows.Forms.MainMenu BaseMenu;
		private System.Windows.Forms.MenuItem FileMenu;
		private System.Windows.Forms.MenuItem LoadNetMenu;
		private System.Windows.Forms.MenuItem SaveNetMenu;
		private System.Windows.Forms.MenuItem ExitMenu;
		private System.Windows.Forms.MenuItem SettingsMenu;
		private System.Windows.Forms.MenuItem CustomizeMenu;
		private System.Windows.Forms.MenuItem SeparetorMenu1;
		private System.Windows.Forms.MenuItem NeuralNetMenu;
		private System.Windows.Forms.MenuItem VerifyMenu;
		private System.Windows.Forms.MenuItem ManageGesturesMenu;
		private System.Windows.Forms.MenuItem ReTrainAllMenu;
		private System.Windows.Forms.SaveFileDialog SaveFullNet;
		private System.Windows.Forms.OpenFileDialog LoadFullNet;
		private System.Windows.Forms.MenuItem menuItem1;
		private System.Windows.Forms.MenuItem ReloadMenu;
		private System.Windows.Forms.MenuItem AboutSoftwareMenu;
		private System.Windows.Forms.MenuItem AboutAuthorMenu;
		private MainBoard m_MainBoard;
		#endregion

		#region Constructor
		public MouseGestureMainForm()
		{
			InitializeComponent();
			this.CustomInitializeComponent();
			this.LinkHandlers();
		}
		#endregion

		#region Dispose function
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}
		#endregion

		#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()
		{
			System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(MouseGestureMainForm));
			this.BaseMenu = new System.Windows.Forms.MainMenu();
			this.FileMenu = new System.Windows.Forms.MenuItem();
			this.LoadNetMenu = new System.Windows.Forms.MenuItem();
			this.SaveNetMenu = new System.Windows.Forms.MenuItem();
			this.ReloadMenu = new System.Windows.Forms.MenuItem();
			this.SeparetorMenu1 = new System.Windows.Forms.MenuItem();
			this.ExitMenu = new System.Windows.Forms.MenuItem();
			this.SettingsMenu = new System.Windows.Forms.MenuItem();
			this.CustomizeMenu = new System.Windows.Forms.MenuItem();
			this.ManageGesturesMenu = new System.Windows.Forms.MenuItem();
			this.NeuralNetMenu = new System.Windows.Forms.MenuItem();
			this.ReTrainAllMenu = new System.Windows.Forms.MenuItem();
			this.VerifyMenu = new System.Windows.Forms.MenuItem();
			this.menuItem1 = new System.Windows.Forms.MenuItem();
			this.AboutSoftwareMenu = new System.Windows.Forms.MenuItem();
			this.AboutAuthorMenu = new System.Windows.Forms.MenuItem();
			this.SaveFullNet = new System.Windows.Forms.SaveFileDialog();
			this.LoadFullNet = new System.Windows.Forms.OpenFileDialog();
			// 
			// BaseMenu
			// 
			this.BaseMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					 this.FileMenu,
																					 this.SettingsMenu,
																					 this.NeuralNetMenu,
																					 this.menuItem1});
			// 
			// FileMenu
			// 
			this.FileMenu.Index = 0;
			this.FileMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					 this.LoadNetMenu,
																					 this.SaveNetMenu,
																					 this.ReloadMenu,
																					 this.SeparetorMenu1,
																					 this.ExitMenu});
			this.FileMenu.Text = "&File";
			// 
			// LoadNetMenu
			// 
			this.LoadNetMenu.Index = 0;
			this.LoadNetMenu.Text = "&Load Net";
			this.LoadNetMenu.Click += new System.EventHandler(this.OnLoadNetMenu);
			// 
			// SaveNetMenu
			// 
			this.SaveNetMenu.Index = 1;
			this.SaveNetMenu.Text = "&Save Net";
			this.SaveNetMenu.Click += new System.EventHandler(this.OnSaveNetMenu);
			// 
			// ReloadMenu
			// 
			this.ReloadMenu.Index = 2;
			this.ReloadMenu.Text = "Reload known gestures";
			this.ReloadMenu.Click += new System.EventHandler(this.OnReloadMenu);
			// 
			// SeparetorMenu1
			// 
			this.SeparetorMenu1.Index = 3;
			this.SeparetorMenu1.Text = "-";
			// 
			// ExitMenu
			// 
			this.ExitMenu.Index = 4;
			this.ExitMenu.Text = "&Exit";
			// 
			// SettingsMenu
			// 
			this.SettingsMenu.Index = 1;
			this.SettingsMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																						 this.CustomizeMenu,
																						 this.ManageGesturesMenu});
			this.SettingsMenu.Text = "&Settings";
			// 
			// CustomizeMenu
			// 
			this.CustomizeMenu.Index = 0;
			this.CustomizeMenu.Text = "&Customize";
			this.CustomizeMenu.Click += new System.EventHandler(this.OnCustomizeMenu);
			// 
			// ManageGesturesMenu
			// 
			this.ManageGesturesMenu.Index = 1;
			this.ManageGesturesMenu.Text = "Manage &gestures";
			// 
			// NeuralNetMenu
			// 
			this.NeuralNetMenu.Index = 2;
			this.NeuralNetMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																						  this.ReTrainAllMenu,
																						  this.VerifyMenu});
			this.NeuralNetMenu.Text = "&Neural Net";
			// 
			// ReTrainAllMenu
			// 
			this.ReTrainAllMenu.Index = 0;
			this.ReTrainAllMenu.Text = "&Train";
			this.ReTrainAllMenu.Click += new System.EventHandler(this.OnReTrainAllMenu);
			// 
			// VerifyMenu
			// 
			this.VerifyMenu.Index = 1;
			this.VerifyMenu.Text = "&Verify";
			this.VerifyMenu.Click += new System.EventHandler(this.OnVerifyMenu);
			// 
			// menuItem1
			// 
			this.menuItem1.Index = 3;
			this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					  this.AboutSoftwareMenu,
																					  this.AboutAuthorMenu});
			this.menuItem1.Text = "&?";
			// 
			// AboutSoftwareMenu
			// 
			this.AboutSoftwareMenu.Index = 0;
			this.AboutSoftwareMenu.Text = "&About Mouse Gesture";
			this.AboutSoftwareMenu.Click += new System.EventHandler(this.OnAboutSoftwareMenu);
			// 
			// AboutAuthorMenu
			// 
			this.AboutAuthorMenu.Index = 1;
			this.AboutAuthorMenu.Text = "&About the Author";
			this.AboutAuthorMenu.Click += new System.EventHandler(this.OnAboutAuthorMenu);
			// 
			// MouseGestureMainForm
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(638, 382);
			this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
			this.Menu = this.BaseMenu;
			this.Name = "MouseGestureMainForm";
			this.Text = "Mouse Gesture";

		}
		#endregion

		#region Custom initialize code
		//In questa funzione inizializzo alcuni componenti appartenenti alla finestra principale
		private void CustomInitializeComponent()
		{
			//Imposto l'oggetto fondamentale del programma: la main board
			this.m_MainBoard= new MainBoard();
			this.SetStyle(ControlStyles.FixedWidth,true);
			this.m_MainBoard.Parent=this;
			this.m_MainBoard.SetBounds(0,0,this.ClientSize.Width,this.ClientSize.Height);
			this.Resize+= new EventHandler(this.m_MainBoard.OnParentResize);
			this.m_MainBoard.Show();

			//Imposto i due dialog per l'apertura e il salvataggio dei files
			this.SaveFullNet.OverwritePrompt=true;
			this.SaveFullNet.FilterIndex=2;
			this.SaveFullNet.Filter="All files (*.*)|*.*|GestureNet files (*.net)|*.net";
			this.SaveFullNet.DefaultExt="net";
			this.SaveFullNet.AddExtension=true;

			this.LoadFullNet.Multiselect=false;
			this.LoadFullNet.FilterIndex=2;
			this.LoadFullNet.Filter="All files (*.*)|*.*|GestureNet files (*.net)|*.net";
			this.LoadFullNet.DefaultExt="net";
			this.LoadFullNet.AddExtension=true;

			this.Text="MouseGesture "+MouseGestureMainForm.Version;
		}
		#endregion
		
		#region Event linking code
		//Associo agli eventi gli handlers
		private void LinkHandlers()
		{
			this.ExitMenu.Click+=new EventHandler(this.OnExitMenu);
			this.ManageGesturesMenu.Click+=new EventHandler(this.OnManageGesturesMenu);
			this.Load+=new EventHandler(this.OnLoad);
			this.Closing+=new CancelEventHandler(this.OnClosing);
			this.m_MainBoard.BeginTraining+=new MouseGesture.MainBoard.BeginTrainingDelegate(this.DeactivateMenus);
			this.m_MainBoard.BeginCreating+=new MouseGesture.MainBoard.BeginCreatingDelegate(this.DeactivateMenus);
			this.m_MainBoard.EndTraining+=new MouseGesture.MainBoard.EndTrainingDelegate(this.ReactivateMenus);
			this.m_MainBoard.EndCreating+=new MouseGesture.MainBoard.EndCreatingDelegate(this.ReactivateMenus);
		}
		#endregion

		#region Event handlers

		#region Menu Handlers
		//Le seguenti funzioni sono gli handler agli eventi del menu
		#region OnExitMenu handler
		private void OnExitMenu(object sender, System.EventArgs e)
		{
			this.Close();
		}
		#endregion

		#region OnManageGesturesMenu handler
		private void OnManageGesturesMenu(object sender, System.EventArgs e)
		{
			this.m_MainBoard.ShowGesturesManagement();
		}
		#endregion

		#region OnReTrainAllMenu handler
		//La funzione addestra le reti delle gestures
		private void OnReTrainAllMenu(object sender, System.EventArgs e)
		{
			ArrayList IndexArray=new ArrayList();
			//Per prima csoa creo un vettore con tutti gli indici delle gestures provviste di training set
			for(int i=0; i<this.m_MainBoard.KnownGestures.Count; i++)
			{
				if(((Gesture)this.m_MainBoard.KnownGestures[i]).TrainingSetCreated)
					IndexArray.Add(i);
			}

			//Se non ci sono gestures con training set non posso eseguire il training
			if(IndexArray.Count<1)
			{
				MessageBox.Show("There are no gestures with a training set.\nTraining is impossible!","Warning!",MessageBoxButtons.OK,MessageBoxIcon.Warning);
				return;
			}

			//Copio l'array dinamico in un array statico
			int[] Indexes=new int[IndexArray.Count];
            IndexArray.CopyTo(Indexes);
            
			//Apro la finestra di training
			NetTrainingForm TrainingForm=new NetTrainingForm(this.m_MainBoard, Indexes);
			this.m_MainBoard.ShowMessageToBar("Training form: open",MessageType.Normal);
			TrainingForm.ShowDialog();
		}
		#endregion

		#region OnVerifyMenu handler
		//La funzione abilita o disabilita il verifying mode al click del tasto
		private void OnVerifyMenu(object sender, System.EventArgs e)
		{
			//Il tasto funzione come un checkbox, perci� controllo prima lo stato attuale del bottone
			if(this.VerifyMenu.Checked)
			{
				//Se � checked, allora mi trovo in verifying mode, quindi esco dalla modalit�
				this.FileMenu.Enabled=true;
				this.SettingsMenu.Enabled=true;
				this.VerifyMenu.Checked=false;
				this.ReTrainAllMenu.Enabled=true;

				this.m_MainBoard.EndVerify();
			}
			else
			{
				//Se non � checked, allora non mi trovo in verifying mode, posso provare ad attivare la modalit�
				//Controllo se almeno una gesture � addestrata
				bool Check=false;

				for(int i=0; i<this.m_MainBoard.KnownGestures.Count && Check==false; i++)
					Check=((Gesture)this.m_MainBoard.KnownGestures[i]).Trained;
				
				//Se esiste una rete addestrata allroa posso entrare nella modalit� di verifica
				if(Check)
				{
					this.FileMenu.Enabled=false;
					this.SettingsMenu.Enabled=false;
					this.VerifyMenu.Checked=true;
					this.ReTrainAllMenu.Enabled=false;

					this.m_MainBoard.StartVerify();
				}
				else
				{
					MessageBox.Show("There is no trained gesture. Train at least a gestures before verifying the net.","Attention!",MessageBoxButtons.OK,MessageBoxIcon.Warning);
				}
			}
		}
		#endregion

		#region DeactivateMenus handler
		//La funzione viene chiamata per disattivare alcuni menu evitando che si possano scegliere
		//alcune modalit� mentre il programma ne sta eseguendo altre
		private void DeactivateMenus()
		{
			this.FileMenu.Enabled=false;
			this.SettingsMenu.Enabled=false;
			this.NeuralNetMenu.Enabled=false;
		}
		#endregion

		#region ReactivateMenus handler
		//La funzione viene chiamata per risattivare alcuni menu che sono stati disattivati
		private void ReactivateMenus()
		{
			this.FileMenu.Enabled=true;
			this.SettingsMenu.Enabled=true;
			this.NeuralNetMenu.Enabled=true;
		}
		#endregion

		#region OnCustomize handler
		//Apre la form di customizzazione
		private void OnCustomizeMenu(object sender, System.EventArgs e)
		{
			CustomizeForm Custom=new CustomizeForm(this.m_MainBoard);
			Custom.ShowDialog();
		}
		#endregion

		#region OnSaveNetMenu handler
		//La funzione salva la rete attuale, intesa come l'insieme delle gestures addestrate attualmente
		private void OnSaveNetMenu(object sender, System.EventArgs e)
		{
			//Conto quante siano le reti addestrate
			int howmany=0;
			for(int i=0; i<this.m_MainBoard.KnownGestures.Count; i++)
			{
				if(((Gesture)this.m_MainBoard.KnownGestures[i]).Trained)
					howmany++;
			}

			//Se non ho almeno una rete il file da salvare � inutile
			if(howmany>0)
			{
				if(this.SaveFullNet.ShowDialog()==DialogResult.OK)
				{
					this.m_MainBoard.SaveFullNet(this.SaveFullNet.FileName);
				}
			}
			else
			{
				MessageBox.Show("There is no trained gesture. Create at least a trained gesture before trying to save a net.","Warning!",MessageBoxButtons.OK,MessageBoxIcon.Warning);
			}
		}
		#endregion

		#region OnLoadNetMenu handler
		//La funzione carica un set di gestures e reti da un file tramite la loading form
		private void OnLoadNetMenu(object sender, System.EventArgs e)
		{
			if(this.LoadFullNet.ShowDialog()==DialogResult.OK)
			{
				LoadingForm ProgDialog=new LoadingForm(this.LoadFullNet.FileName,this.m_MainBoard);
				ProgDialog.ShowDialog();
			}
		}
		#endregion

		#region OnReloadMenu handler
		//La funzione permette di caricare nuovamente tutte le gestures presenti nella cartella Gestures
		//la funzione � utile per caricare nuove gesture inserite manualmente durante la sessione corrente
		//o per ricaricare alcune gestures precedentemente escluse tramite il menu 'Manage gestures'
		private void OnReloadMenu(object sender, System.EventArgs e)
		{
			LoadingForm ProgDialog=new LoadingForm(this.m_MainBoard);
			ProgDialog.ShowDialog();
		}
		#endregion

		#region OnAboutSoftwareMenu handler
		//Funzione per la visualizzazione delle informazioni relative all'applicazione
		private void OnAboutSoftwareMenu(object sender, System.EventArgs e)
		{
			MessageBox.Show("MouseGesture "+MouseGestureMainForm.Version+" [10/08/2004]","About MouseGesture",MessageBoxButtons.OK,MessageBoxIcon.Information);
		}
		#endregion

		#region OnAboutAuthorMenu handler
		//Funzione per la visualizzazione delle informazioni relative all'autore
		private void OnAboutAuthorMenu(object sender, System.EventArgs e)
		{
			MessageBox.Show("Author: Daniele Mancini\nE-mail: dany2222@libero.it\nCountry: Italy\nProfession: Student (Computer Engineering)","About the Author",MessageBoxButtons.OK,MessageBoxIcon.Information);
		}
		#endregion

		#endregion

		#region Form events
		
		#region OnLoad handler
		//Al caricamento dell'applicazione eseguo il load delle gestures nella directory ./Gestures/
		//tramite la LoadingForm, che si occupa di gestire i caricamenti lunghi e i processi che
		//possono impiegare un tempo piuttosto elevato
		private void OnLoad(object obj, EventArgs e)
		{
			LoadingForm ProgDialog=new LoadingForm(this.m_MainBoard);
			ProgDialog.ShowDialog();
		}
		#endregion

		#region OnClosing handler
		//Durante il training voglio evitare che il programma possa essere chiuso (corrompendo i dati salvati)
		private void OnClosing(object sender, CancelEventArgs e)	
		{
			if(this.m_MainBoard.BState==BoardState.Training)
			{
				e.Cancel=true;
			}
		}
		#endregion

		#endregion

		#endregion

		#region Main function
		//La funzione che avvia realmente il programma
		[STAThread]
		static void Main() 
		{
			Application.Run(new MouseGestureMainForm());
		}
		#endregion
	}
	#endregion
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Apex s.r.l.
Italy Italy
I got my Computer Science (Engineering) Master's Degree at the Siena University (Italy), but I'm from Rieti (a small town next to Rome).
My hobbies are RPG, MMORGP, programming and 3D graphics.
At the moment I'm employed at Apex s.r.l. (Modena, Italy) as a senior software developer, working for a WPF/WCF project in Rome.

Comments and Discussions