begin process at 2008 09 06 05:23:16
1 237 646 membres
44 nouveaux aujourd'hui
14 313 membres club

Vous ne trouvez pas de réponse à votre problème ? Alors posez la question dans le forum.
Souvenez-vous qu'il n'y a jamais de question bête, mais rester dans l'ignorance parce que l'on n'ose pas poser une question, ça c'est une erreur !

ILISTBOX : UNE LISTE BOX PILOTABLE AU DOIGT


Information sur la source

Catégorie :PPC :: Divers Source .NET ( DotNet ) Classé sous : listbox, pocketpc, iphone, scrolling, ihm Niveau : Débutant Date de création : 07/08/2007 Date de mise à jour : 23/09/2007 15:24:06 Vu : 7 982

Note :
8 / 10 - par 1 personne
8,00 / 10

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

Commentaire sur cette source (1)
Ajouter un commentaire et/ou une note


Description

Les listBox sur pocketPC sont assez difficiles à utiliser avec les doigts, elles ont été crées pour être utilisées à l'aide d'un stylet.
Une IHM pilotable avec le doigt est très pratique dans de nombreux logiciels comme les télécommandes par exemple. J'ai donc écrit ce petit bout de code afin de démontrer que très peu de lignes sont nécessaires à la réalisation d'une Listbox à la iPhone. La source est très simple afin que même les débutant puissent s'y retrouver.
Cette source a été testée sur l'émulateur pocket Pc de Visual Studio  2003, il fonctionne avec le compact framework 1 ainsi que sur mon qtek 9100.

Source

  • using System;
  • using System.Drawing;
  • using System.Windows.Forms;
  • using System.Threading;
  • namespace DodgerCodeSnippets
  • {
  • /// <summary>
  • /// Description résumée de FormMain.
  • /// </summary>
  • public class FormMain : System.Windows.Forms.Form
  • {
  • private Bitmap offScreenBitmap;
  • private Graphics offScreenGraphics; // Représenta la zone dans laquelle on dessine les items
  • private Graphics onScreenGraphics; // Représenta la zone réellement affichée
  • private bool m_bSelectionDone = false;
  • private int m_iScreenWidth = 240; // Taille de l'écran
  • private int m_iScreenHeight = 320;
  • private int m_iItemsCount = 40; // Nombre d'Item dans la liste
  • private int m_iItemheight = 40; // auteur d'un item
  • private int m_iStripWidth = 240;
  • private int m_iStripHeight = 320; // Hauteur totale de la liste
  • private int m_iStripPosY = 1;
  • private int m_iOldStripPosY = -10;
  • private int m_iMoveStep = 1; // Déplacement en nombre de pixels à chaque boucle
  • private int m_iSens = 0; // 0,+1,-1
  • private int m_iTouchStartY = 0; // Position en pixel de l'endroit où l'on a posé le doigt
  • private int m_iTouchEndY = 0; // Position en pixel de l'endroit où l'on a relevé le doigt
  • private int m_iSelectedIndexItem = -1; // Numéro de l'Item sélectionné
  • private int m_iPixelPerScroll = 0; // De combien de pixel doit on scrollé après un mouvement de doigt sur l'écran
  • private int m_iSleep = 3; // nombre de milliseconde d'attente dans la boucle
  • public static System.Drawing.Color OddCellBackGroundColor = System.Drawing.Color.LightGray;
  • public static System.Drawing.Color EvenCellBackGroundColor = System.Drawing.Color.DarkSeaGreen;
  • public static System.Drawing.Color SelectedCellBackGroundColor = System.Drawing.Color.CornflowerBlue;
  • public static System.Drawing.Color CellBorderColor = System.Drawing.Color.ForestGreen;
  • public FormMain()
  • {
  • //
  • // Requis pour la prise en charge du Concepteur Windows Forms
  • //
  • InitializeComponent();
  • InitScreens ();
  • DoLoop();
  • }
  • private void InitScreens ()
  • {
  • this.Visible = true;
  • this.WindowState = FormWindowState.Maximized;
  • m_iStripHeight = m_iItemsCount*m_iItemheight;
  • // Creation d'un ecran virtuel plus grand que l'écran du PDA qui contient toute la liste
  • offScreenBitmap = new Bitmap(m_iStripWidth, m_iStripHeight);
  • offScreenGraphics = Graphics.FromImage(offScreenBitmap);
  • offScreenGraphics.Clear(Color.Black);
  • onScreenGraphics = this.CreateGraphics();
  • }
  • private void DoLoop()
  • {
  • // C'est ici que l'on dessine les Items
  • for (int iItem=0; iItem<m_iItemsCount ; iItem++)
  • DrawItem(iItem);
  • onScreenGraphics.Clear(Color.Black);
  • onScreenGraphics.DrawImage(offScreenBitmap, 0, 0, new Rectangle(0,0,240,320), GraphicsUnit.Pixel);
  • Application.DoEvents();
  • Render();
  • onScreenGraphics.Dispose();
  • Application.DoEvents();
  • MessageBox.Show("Vous avez sélectionné l'item : " + m_iSelectedIndexItem, "Info");
  • Application.Exit();
  • }
  • /// <summary>
  • /// Nettoyage des ressources utilisées.
  • /// </summary>
  • protected override void Dispose( bool disposing )
  • {
  • base.Dispose( disposing );
  • }
  • #region Code généré par le Concepteur Windows Form
  • /// <summary>
  • /// Méthode requise pour la prise en charge du concepteur - ne modifiez pas
  • /// le contenu de cette méthode avec l'éditeur de code.
  • /// </summary>
  • private void InitializeComponent()
  • {
  • //
  • // FormMain
  • //
  • this.ClientSize = new System.Drawing.Size(229, 270);
  • this.Text = "iListBox";
  • this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.FormMain_MouseDown);
  • this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.FormMain_MouseUp);
  • }
  • #endregion
  • /// <summary>
  • /// Point d'entrée principal de l'application.
  • /// </summary>
  • static void Main()
  • {
  • Application.Run(new FormMain());
  • }
  • /// <summary>
  • /// Boucle principale de rendu de la liste
  • /// </summary>
  • protected virtual void Render()
  • {
  • // distance parcourrue en pixel depuis le dernier mouvement de doigt
  • int iPixelScrollCount = 0;
  • while (!m_bSelectionDone)
  • {
  • try
  • {
  • // On bloque le scroll quand on arrive en bas
  • if ( (m_iSens == 1 ) && (m_iStripPosY + m_iScreenHeight >= m_iStripHeight ))
  • {
  • m_iSens = 0;
  • iPixelScrollCount = 0;
  • }
  • // On bloque le scroll quand on arrive en haut
  • if ( (m_iSens == -1 ) && (m_iStripPosY <= 0 ))
  • {
  • m_iSens = 0;
  • iPixelScrollCount = 0;
  • }
  • if ( m_iSens != 0 )
  • {
  • iPixelScrollCount++;
  • m_iStripPosY += m_iMoveStep*m_iSens;
  • }
  • // Si on a scrollé du nombre de pixel que l'on souhaitait
  • // On s'arrete
  • if ( iPixelScrollCount > m_iPixelPerScroll )
  • {
  • m_iSens = 0;
  • iPixelScrollCount = 0;
  • }
  • // Si on a pas bougé, inutile de re-dessiner
  • if ( m_iOldStripPosY != m_iStripPosY )
  • {
  • onScreenGraphics.DrawImage(offScreenBitmap, 0, 0, new Rectangle(0,m_iStripPosY,240,320), GraphicsUnit.Pixel);
  • m_iOldStripPosY = m_iStripPosY;
  • }
  • Application.DoEvents(); // On laisse le temps au PDA de souffler
  • Thread.Sleep(m_iSleep); // On ralentit quelque peu le scrolling
  • }
  • catch(Exception exp)
  • {
  • MessageBox.Show("Oups il y a un problème dans Render :" + exp.ToString());
  • }
  • }
  • }
  • /// <summary>
  • /// Dessine un Item ( élément ) de la liste à la position indiquée
  • /// </summary>
  • /// <param name="iIndex"></param>
  • private void DrawItem (int iIndex )
  • {
  • Font font;
  • string text;
  • Brush blackBrush = new SolidBrush(Color.Black);
  • Brush brushOdd = new SolidBrush(OddCellBackGroundColor);
  • Brush brushEven = new SolidBrush(EvenCellBackGroundColor);
  • Brush brush = null;
  • font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Bold);
  • Pen pen = new Pen(CellBorderColor);
  • // On intervertit les couleurs pour donner un coté sympa
  • if ( (iIndex % 2) == 0 )
  • brush = brushOdd;
  • else
  • brush = brushEven;
  • offScreenGraphics.FillRectangle(brush,0,iIndex*m_iItemheight,m_iScreenWidth-1,m_iItemheight);
  • offScreenGraphics.DrawRectangle(pen,0,iIndex*m_iItemheight,m_iScreenWidth,m_iItemheight);
  • // C'est ici que vous insérez le texte que vous souhaitez
  • text = string.Format("Item {0}", iIndex);
  • offScreenGraphics.DrawString(text, font, blackBrush, 5, (iIndex*m_iItemheight)+10);
  • }
  • /// <summary>
  • /// Dessine un Item sélectionné à la position indiquée
  • /// </summary>
  • /// <param name="iIndex"></param>
  • private void DrawSelectedItem (int iIndex )
  • {
  • Font font;
  • string text;
  • Pen pen = new Pen(CellBorderColor);
  • Brush blackBrush = new SolidBrush(Color.Black);
  • font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Bold);
  • // On dessine le rectangle plein
  • offScreenGraphics.FillRectangle(new SolidBrush(SelectedCellBackGroundColor),0,iIndex*m_iItemheight,m_iScreenWidth-1,m_iItemheight);
  • // avec un petit contour vert
  • offScreenGraphics.DrawRectangle(pen,0,iIndex*m_iItemheight,m_iScreenWidth,m_iItemheight);
  • text = string.Format("Item {0}", iIndex);
  • // On affiche le texte
  • offScreenGraphics.DrawString(text, font, blackBrush, 5, (iIndex*m_iItemheight)+10);
  • m_iOldStripPosY = -1; // Force à redessiner ( voir méthode Render() )
  • }
  • // Gestion du scroll au doigt et à l'oeuil ... heu non au stylet !
  • private void FormMain_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
  • {
  • m_iTouchEndY = e.Y;
  • if ( m_iSens == 0 )
  • {
  • if ( m_iTouchStartY-m_iTouchEndY > 0 )
  • m_iSens=-1;
  • else
  • m_iSens=1;
  • int iDelta = Math.Abs(m_iTouchStartY-m_iTouchEndY);
  • // Plus le doigt a glissé sur une grande distance,
  • // plus on scroll loin
  • if ( iDelta > 80 )
  • {
  • m_iPixelPerScroll = 320;
  • m_iSleep = 0;
  • }
  • else
  • if ( ( iDelta > 50 ) && ( iDelta < 80 ))
  • {
  • m_iPixelPerScroll = 160;
  • m_iSleep = 2;
  • }
  • else
  • if ( ( iDelta < 50 ) && ( iDelta > 10 ))
  • {
  • m_iPixelPerScroll = 80;
  • m_iSleep = 4;
  • }
  • else
  • {
  • // On commence par effacer le précédent item sélectionné si il existe
  • int iPreviousSelectionIndex = m_iSelectedIndexItem;
  • if ( m_iSelectedIndexItem > -1 )
  • DrawItem(iPreviousSelectionIndex);
  • m_iSens =0;
  • m_iSelectedIndexItem = (m_iStripPosY+m_iTouchEndY)/m_iItemheight;
  • DrawSelectedItem(m_iSelectedIndexItem);
  • if ( iPreviousSelectionIndex == m_iSelectedIndexItem )
  • m_bSelectionDone = true;
  • }
  • m_iTouchStartY = 0;
  • m_iTouchEndY = 0;
  • }
  • else // si on touche l'écran pendant le scroll, ça l'arrete
  • m_iSens =0;
  • }
  • private void FormMain_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
  • {
  • m_iTouchStartY = e.Y;
  • }
  • }
  • }
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;

namespace DodgerCodeSnippets
{
	/// <summary>
	/// Description résumée de FormMain.
	/// </summary>
	public class FormMain : System.Windows.Forms.Form
	{

		private Bitmap offScreenBitmap;
		private Graphics offScreenGraphics;	// Représenta la zone dans laquelle on dessine les items
		private Graphics onScreenGraphics;  // Représenta la zone réellement affichée
		
		private bool m_bSelectionDone = false;
		
		private int m_iScreenWidth = 240;	// Taille de l'écran
		private int m_iScreenHeight = 320;	
		
		private int m_iItemsCount = 40;		// Nombre d'Item dans la liste
		private int m_iItemheight = 40;		// auteur d'un item

		private int m_iStripWidth = 240;
		private int m_iStripHeight = 320;   // Hauteur totale de la liste 
				
		private int m_iStripPosY = 1;
		private int m_iOldStripPosY = -10;
		
		private int m_iMoveStep = 1;		// Déplacement en nombre de pixels à chaque boucle
		private int m_iSens = 0;			// 0,+1,-1 
				
		private int m_iTouchStartY = 0;		// Position en pixel de l'endroit où l'on a posé le doigt
		private int m_iTouchEndY = 0;		// Position en pixel de l'endroit où l'on a relevé le doigt
		
		private int m_iSelectedIndexItem = -1;	// Numéro de l'Item sélectionné 
		
		private int m_iPixelPerScroll = 0;  // De combien de pixel doit on scrollé après un mouvement de doigt sur l'écran
		
		private int m_iSleep = 3;			// nombre de milliseconde d'attente dans la boucle

		public static System.Drawing.Color OddCellBackGroundColor = System.Drawing.Color.LightGray;
		public static System.Drawing.Color EvenCellBackGroundColor = System.Drawing.Color.DarkSeaGreen; 
		public static System.Drawing.Color SelectedCellBackGroundColor = System.Drawing.Color.CornflowerBlue;
		public static System.Drawing.Color CellBorderColor = System.Drawing.Color.ForestGreen;
				
		public FormMain()
		{
			//
			// Requis pour la prise en charge du Concepteur Windows Forms
			//
			InitializeComponent();

			InitScreens ();
			DoLoop();
		}

		private void InitScreens ()
		{
			this.Visible = true;			
			this.WindowState = FormWindowState.Maximized;	
			m_iStripHeight = m_iItemsCount*m_iItemheight;
			// Creation d'un ecran virtuel plus grand que l'écran du PDA qui contient toute la liste		
			offScreenBitmap = new Bitmap(m_iStripWidth, m_iStripHeight);	
			offScreenGraphics = Graphics.FromImage(offScreenBitmap);
			offScreenGraphics.Clear(Color.Black);	
			onScreenGraphics = this.CreateGraphics();			
		}


		private void DoLoop()
		{			
			// C'est ici que l'on dessine les Items
			for (int iItem=0; iItem<m_iItemsCount ; iItem++)
				DrawItem(iItem);		

			onScreenGraphics.Clear(Color.Black);
			onScreenGraphics.DrawImage(offScreenBitmap, 0, 0, new Rectangle(0,0,240,320), GraphicsUnit.Pixel);													
			Application.DoEvents();	
			
			Render();
									
			onScreenGraphics.Dispose();
			Application.DoEvents();
			MessageBox.Show("Vous avez sélectionné l'item : " + m_iSelectedIndexItem, "Info");
			Application.Exit();
		}				

		/// <summary>
		/// Nettoyage des ressources utilisées.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			base.Dispose( disposing );
		}
		#region Code généré par le Concepteur Windows Form
		/// <summary>
		/// Méthode requise pour la prise en charge du concepteur - ne modifiez pas
		/// le contenu de cette méthode avec l'éditeur de code.
		/// </summary>
		private void InitializeComponent()
		{
			// 
			// FormMain
			// 
			this.ClientSize = new System.Drawing.Size(229, 270);
			this.Text = "iListBox";
			this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.FormMain_MouseDown);
			this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.FormMain_MouseUp);

		}
		#endregion

		/// <summary>
		/// Point d'entrée principal de l'application.
		/// </summary>

		static void Main() 
		{
			Application.Run(new FormMain());
		}		

		/// <summary>
		/// Boucle principale de rendu de la liste
		/// </summary>
		protected virtual void Render()
		{								
			// distance parcourrue en pixel depuis le dernier mouvement de doigt
			int iPixelScrollCount = 0;						
			while (!m_bSelectionDone) 
			{
				try
				{
					// On bloque le scroll quand on arrive en bas
					if ( (m_iSens == 1 ) && (m_iStripPosY + m_iScreenHeight >= m_iStripHeight ))
					{
						m_iSens = 0;	
						iPixelScrollCount = 0;						
					}
					// On bloque le scroll quand on arrive en haut
					if ( (m_iSens == -1 ) && (m_iStripPosY <= 0 ))
					{
						m_iSens = 0;
						iPixelScrollCount = 0;						
					}
					
					if ( m_iSens != 0 )
					{
						iPixelScrollCount++;
						m_iStripPosY += m_iMoveStep*m_iSens;
					}

					// Si on a scrollé du nombre de pixel que l'on souhaitait 
					// On s'arrete
					if ( iPixelScrollCount > m_iPixelPerScroll )
					{
						m_iSens = 0;
						iPixelScrollCount = 0;
					}					
					
					// Si on a pas bougé, inutile de re-dessiner
					if ( m_iOldStripPosY != m_iStripPosY )
					{
						onScreenGraphics.DrawImage(offScreenBitmap, 0, 0, new Rectangle(0,m_iStripPosY,240,320), GraphicsUnit.Pixel);													
						m_iOldStripPosY = m_iStripPosY;							
					}					
					Application.DoEvents();		// On laisse le temps au PDA de souffler 
					Thread.Sleep(m_iSleep);		// On ralentit quelque peu le scrolling
				}
				catch(Exception exp)
				{
					MessageBox.Show("Oups il y a un problème dans Render :" + exp.ToString());
				}
			}
		}

		/// <summary>
		/// Dessine un Item ( élément ) de la liste à la position indiquée
		/// </summary>
		/// <param name="iIndex"></param>
		private void DrawItem (int iIndex )
		{
			Font font;					
			string text;

			Brush blackBrush = new SolidBrush(Color.Black);
			Brush brushOdd = new SolidBrush(OddCellBackGroundColor);
			Brush brushEven = new SolidBrush(EvenCellBackGroundColor);
			Brush brush = null;
			font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Bold);	
			Pen pen = new Pen(CellBorderColor);		
			// On intervertit les couleurs pour donner un coté sympa
			if ( (iIndex % 2) == 0 )
				brush = brushOdd;
			else
				brush = brushEven;
			offScreenGraphics.FillRectangle(brush,0,iIndex*m_iItemheight,m_iScreenWidth-1,m_iItemheight);
			offScreenGraphics.DrawRectangle(pen,0,iIndex*m_iItemheight,m_iScreenWidth,m_iItemheight);
			// C'est ici que vous insérez le texte que vous souhaitez
			text = string.Format("Item {0}", iIndex);
			offScreenGraphics.DrawString(text, font, blackBrush, 5, (iIndex*m_iItemheight)+10);	
		}

		/// <summary>
		/// Dessine un Item sélectionné à la position indiquée
		/// </summary>
		/// <param name="iIndex"></param>
		private void DrawSelectedItem (int iIndex )
		{
			Font font;					
			string text;			
			Pen pen = new Pen(CellBorderColor);		
			Brush blackBrush = new SolidBrush(Color.Black);
			font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Bold);	
			// On dessine le rectangle plein
			offScreenGraphics.FillRectangle(new SolidBrush(SelectedCellBackGroundColor),0,iIndex*m_iItemheight,m_iScreenWidth-1,m_iItemheight);
			// avec un petit contour vert
			offScreenGraphics.DrawRectangle(pen,0,iIndex*m_iItemheight,m_iScreenWidth,m_iItemheight);
			text = string.Format("Item {0}", iIndex);
			// On affiche le texte
			offScreenGraphics.DrawString(text, font, blackBrush, 5, (iIndex*m_iItemheight)+10);	
			m_iOldStripPosY = -1; // Force à redessiner ( voir méthode Render() )
		}
		
		// Gestion du scroll au doigt et à l'oeuil ... heu non au stylet !
		private void FormMain_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
		{			
			m_iTouchEndY = e.Y;
			if ( m_iSens == 0 )
			{
				if ( m_iTouchStartY-m_iTouchEndY > 0 )
					m_iSens=-1;
				else
					m_iSens=1;
				int iDelta = Math.Abs(m_iTouchStartY-m_iTouchEndY);
				// Plus le doigt a glissé sur une grande distance, 
				// plus on scroll loin
				if ( iDelta > 80 )
				{
					m_iPixelPerScroll = 320;
					m_iSleep = 0;
				}
				else
					if ( ( iDelta > 50 )  && ( iDelta < 80 ))
				{
					m_iPixelPerScroll = 160;
					m_iSleep = 2;
				}
				else
					if ( ( iDelta < 50 ) && ( iDelta > 10 ))
				{
					m_iPixelPerScroll = 80;
					m_iSleep = 4;
				}
				else
				{
					// On commence par effacer le précédent item sélectionné si il existe
					int iPreviousSelectionIndex = m_iSelectedIndexItem;
					if ( m_iSelectedIndexItem > -1 )
						DrawItem(iPreviousSelectionIndex);
					m_iSens =0;					
					m_iSelectedIndexItem = (m_iStripPosY+m_iTouchEndY)/m_iItemheight;
					DrawSelectedItem(m_iSelectedIndexItem);
					if ( iPreviousSelectionIndex == m_iSelectedIndexItem )
						m_bSelectionDone = true;
				}

				m_iTouchStartY = 0;
				m_iTouchEndY = 0;
			}
			else	// si on touche l'écran pendant le scroll, ça l'arrete
				m_iSens =0;
		}

		private void FormMain_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
		{			
			m_iTouchStartY = e.Y;		
		}
	}
}

Conclusion

Vous pouvez compiler cette source en ligne de commande via :

csc.exe /target:exe /out:iListBox.exe /r:System.dll,System.Drawing.dll,System.Windows.Forms.dll FormMain.cs
Vous devez avoir les assemblies de votre pocket pc dans le même répertoire que la source

Je pense faire évoluer cette iListBox vers une iListView avec des images et plusieurs colonnes.

Quelques une de mes réalisations peuvent être téléchargées sur http://dodgersflasks.blogspot.com/
07 août 2007 14:50:27 :
orthographe
  • signaler à un administrateur
    Commentaire de psykocouac le 07/11/2007 17:50:23 8/10

    Code très interessant !!

    Pensez-vous qu'il soit possible d'externaliser cette IListe dans un UserControl. J'ai essayé en copiant naïvement le code dans un UserControl mais il semblerait que la boucle active ne soit pas bien supportée.

    De manière générale, comment le PDA réagit lorsqu'on donne à une WindowsForm un Control exécutant du contenu dynamique ?

    Merci pour ces informations

Ajouter un commentaire

Discussions en rapport avec ce code source

Pub



Appels d'offres

CalendriCode

Septembre 2008
LMMJVSD
1234567
891011121314
15161718192021
22232425262728
2930     

Téléchargements

Logiciels à télécharger sur le même thème :

Boutique

Boutique de goodies CodeS-SourceS