Accueil > > > EXEMPLE D'UTILISATION DE CONTROL.INVOKE
EXEMPLE D'UTILISATION DE CONTROL.INVOKE
Information sur la source
Description
Suite à question(s) sur le forum : Juste un petit exemple d'utilisation de la méthode Control.Invoke (http://msdn.microsoft.com/fr-fr/library/system.wi ndows.forms.control.invoke.aspx) pour manipuler un contrôle depuis un autre thread que celui qui l'a crée. Je vous met l'intégralité du code du Form, juste un petit c/c et c'est bon :-)
Source
- using System;
- using System.Drawing;
- using System.Collections;
- using System.ComponentModel;
- using System.Windows.Forms;
- using System.Data;
- using System.Threading;
-
- namespace ControlInvokeSample
- {
- public class Form1 : System.Windows.Forms.Form
- {
- private System.Windows.Forms.Label label_Affichage;
- private System.Windows.Forms.Button button_Start;
- private System.ComponentModel.Container components = null;
-
- public Form1()
- {
- InitializeComponent();
- }
-
- protected override void Dispose( bool disposing )
- {
- if( disposing )
- {
- if (components != null)
- {
- components.Dispose();
- }
- }
- 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()
- {
- this.label_Affichage = new System.Windows.Forms.Label();
- this.button_Start = new System.Windows.Forms.Button();
- this.SuspendLayout();
- //
- // label_Affichage
- //
- this.label_Affichage.Location = new System.Drawing.Point(8, 40);
- this.label_Affichage.Name = "label_Affichage";
- this.label_Affichage.Size = new System.Drawing.Size(472, 72);
- this.label_Affichage.TabIndex = 0;
- //
- // button_Start
- //
- this.button_Start.Location = new System.Drawing.Point(8, 8);
- this.button_Start.Name = "button_Start";
- this.button_Start.TabIndex = 1;
- this.button_Start.Text = "Start";
- this.button_Start.Click += new System.EventHandler(this.button_Start_Click);
- //
- // Form1
- //
- this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
- this.ClientSize = new System.Drawing.Size(488, 117);
- this.Controls.Add(this.button_Start);
- this.Controls.Add(this.label_Affichage);
- this.Name = "Form1";
- this.Text = "Form1";
- this.ResumeLayout(false);
-
- }
- #endregion
-
- [STAThread]
- static void Main()
- {
- Application.Run(new Form1());
- }
-
- // ****************
- // définition du delegate qui sera utilisé
- private delegate void UpdateLabelDelegate ( string text );
- // ****************
-
- private UpdateLabelDelegate m_upLbl;
- private Thread m_monThread;
-
-
- private void button_Start_Click(object sender, System.EventArgs e)
- {
- button_Start.Enabled = false;
-
- // affectation du nom du thread courant
- Thread.CurrentThread.Name = "Thread principal";
-
- // initialisation de l'instance de UpdateLabelDelegate qui sera utilisée dans le thread
- m_upLbl = new UpdateLabelDelegate(this.MaMethodeDeMajDuLabel);
-
- // création et lancement du thread "supplémentaire"
- m_monThread = new Thread(new ThreadStart(this.ThreadProc));
- m_monThread.Name = "Thread supplémentaire";
- m_monThread.Start();
- }
-
- private void ThreadProc()
- {
- // le tableau d'object qui sera utilisé pour le passage des paramètres.
- object [] args = new object[1];
-
- for ( int i=0; i<=10; i++)
- {
- // affectation du texte, c'est lui qui sera reçu en paramètre "text" de notre méthode
- args[0] = string.Format("{0} (depuis : {1})", i.ToString(), Thread.CurrentThread.Name);
-
- // ****************
- label_Affichage.Invoke(m_upLbl, args);
- // ****************
-
- // petite pause
- Thread.Sleep(500);
- }
-
- args[0] = string.Format("C'est fini :-) (depuis : {0})", Thread.CurrentThread.Name);
- label_Affichage.Invoke(m_upLbl, args);
- }
-
- // ****************
- // la méthode correspondant à la déclaration de UpdateLabelDelegate
- // qui fera la MAJ du texte du Label dans le thread auquel appartient le contrôle.
- private void MaMethodeDeMajDuLabel(string text)
- {
- // MAJ du texte en ajoutant le nom du thread depuis lequel cette maj est faite.
- label_Affichage.Text = string.Format("{0}\r\nLabel mis à jour depuis : {1}", text, Thread.CurrentThread.Name);
- }
- // ****************
- }
- }
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;
namespace ControlInvokeSample
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Label label_Affichage;
private System.Windows.Forms.Button button_Start;
private System.ComponentModel.Container components = null;
public Form1()
{
InitializeComponent();
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
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()
{
this.label_Affichage = new System.Windows.Forms.Label();
this.button_Start = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label_Affichage
//
this.label_Affichage.Location = new System.Drawing.Point(8, 40);
this.label_Affichage.Name = "label_Affichage";
this.label_Affichage.Size = new System.Drawing.Size(472, 72);
this.label_Affichage.TabIndex = 0;
//
// button_Start
//
this.button_Start.Location = new System.Drawing.Point(8, 8);
this.button_Start.Name = "button_Start";
this.button_Start.TabIndex = 1;
this.button_Start.Text = "Start";
this.button_Start.Click += new System.EventHandler(this.button_Start_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(488, 117);
this.Controls.Add(this.button_Start);
this.Controls.Add(this.label_Affichage);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
// ****************
// définition du delegate qui sera utilisé
private delegate void UpdateLabelDelegate ( string text );
// ****************
private UpdateLabelDelegate m_upLbl;
private Thread m_monThread;
private void button_Start_Click(object sender, System.EventArgs e)
{
button_Start.Enabled = false;
// affectation du nom du thread courant
Thread.CurrentThread.Name = "Thread principal";
// initialisation de l'instance de UpdateLabelDelegate qui sera utilisée dans le thread
m_upLbl = new UpdateLabelDelegate(this.MaMethodeDeMajDuLabel);
// création et lancement du thread "supplémentaire"
m_monThread = new Thread(new ThreadStart(this.ThreadProc));
m_monThread.Name = "Thread supplémentaire";
m_monThread.Start();
}
private void ThreadProc()
{
// le tableau d'object qui sera utilisé pour le passage des paramètres.
object [] args = new object[1];
for ( int i=0; i<=10; i++)
{
// affectation du texte, c'est lui qui sera reçu en paramètre "text" de notre méthode
args[0] = string.Format("{0} (depuis : {1})", i.ToString(), Thread.CurrentThread.Name);
// ****************
label_Affichage.Invoke(m_upLbl, args);
// ****************
// petite pause
Thread.Sleep(500);
}
args[0] = string.Format("C'est fini :-) (depuis : {0})", Thread.CurrentThread.Name);
label_Affichage.Invoke(m_upLbl, args);
}
// ****************
// la méthode correspondant à la déclaration de UpdateLabelDelegate
// qui fera la MAJ du texte du Label dans le thread auquel appartient le contrôle.
private void MaMethodeDeMajDuLabel(string text)
{
// MAJ du texte en ajoutant le nom du thread depuis lequel cette maj est faite.
label_Affichage.Text = string.Format("{0}\r\nLabel mis à jour depuis : {1}", text, Thread.CurrentThread.Name);
}
// ****************
}
}
Conclusion
Voir aussi le tuto de Mx : http://www.csharpfr.com/tutorial.aspx?ID=174
Historique
- 21 novembre 2005 18:13:02 :
- ajout des mots clés
- 11 mars 2006 15:51:19 :
- Suppression de quelques horribles concaténations de chaînes ^^
- 04 mai 2008 17:03:12 :
- Changement liens vers MSDN suite au shutdown complet de l'ancienne version (et des redirections).
Sources du même auteur
Sources de la même categorie
Commentaires et avis
Discussions en rapport avec ce code source dans le forum
Ajout d'un contrôle depuis un thread en utilisant Invoke... [ par gazous ]
Bonjour,Je vous contacte car j'ai vu que vous étiez assez calé en dll.Mon problème :J'ai un thread qui essaye d'ajouter un contrôle dans un panel char
Thread - Controls [ par bucherb ]
Hello!J'ai un petit problème.. Je souhaite créer un control dans un Thread séparé du Thread principal... Comment est-ce que je peu
Thread et control [ par RMI ]
Bonjour, Voila mon problème: J'ai une form avec un tabcontrol Les 2 premières tabpages sont rempli dans le load du winform la 3ème con
Cross-Threading -> Exception [ par sebseb42 ]
salut a tousvoila mon probleme est simple, dans ma classe principal, je lance un thread, et dans ce thread j'essaye de modifier un controle.ca fonctio
Cross-threading [ par CMatt ]
Bonjour, j'ai une application console qui utilise un thread pour écouter des données en provenance d'un socket réseau. Ce que je voudr
Ce qu'on a le droit et pas le droit dans un thread... [ par cyrare ]
Bonjour,On voit pas mal de problèmes liés au cross threading, et à chacun de ces problèmes, un rapide tour sur le tuto de ce site
Cross thread problème [ par WishhhMaster ]
Bonjour,J'ai un petit problème lié au cross threading. Dans mon application, l'utilisateur choisit divers fichiers images, dont les miniatures sont e
Equivalent à Control.Invoke? [ par leprov ]
Existe-t-il un équivalent à la méthode control.invoke qui aie la meme fonctionnalité, mais lorsque l'on ne dispose pas d'un controle? c'est plus une c
Threading sur le .NET CF [ par t00f ]
Bonjour à tous, Je viens vers vous car j'ai une question qui peut paraitre stupide mais sincère : Je cherche a créer un Control personnalisé (type c
Thread et création de control [ par Bhaal_DtC ]
Tout d'abors je vais résumer ma situation le plus clairement possible. j'utilise un thread spécifique pour lire des données dans le cad
|
Derniers Blogs
[MIX10] KEYNOTE DEUXIèME JOURNéE - INTERNET EXPLORER 9, HTML5, VISUAL STUDIO 2010, ODATA[MIX10] KEYNOTE DEUXIèME JOURNéE - INTERNET EXPLORER 9, HTML5, VISUAL STUDIO 2010, ODATA par cyril
Le deuxième keynote du mix fut très riche en contenu. Internet Explorer 9 Juste un après le lancement de Internet Explorer 8, Microsoft a dévoilé les nouveautés de Internet Explorer 9. Désormais, IE supportera HTML5, SVG et CSS3. L'élément ...
Cliquez pour lire la suite de l'article par cyril CERTIFICATIONS BETA .NET 4CERTIFICATIONS BETA .NET 4 par KooKiz
Les inscriptions pour les certifications beta .NET 4 ont commencé. L'inscription est offerte pour les examens suivants : - 71-511, TS: Windows Applications Development with Microsoft .NET Framework 4 - 71-515, TS: Web Applications Development with...
Cliquez pour lire la suite de l'article par KooKiz [MIX 2010] - MICROSOFT TRANSLATOR TECHNOLOGY PREVIEW V2[MIX 2010] - MICROSOFT TRANSLATOR TECHNOLOGY PREVIEW V2 par redo
J'imagine que la plupart d'entre vous connaissent bien et utilisent le service de traduction de Google, mais connaissez-vous celui de Microsoft . Microsoft Translator ? Effectivement, Microsoft nous annoncé le lancement version 2 de la Technologie Preview...
Cliquez pour lire la suite de l'article par redo LANCEMENT EN PREVIEW DE CYCLONE LORS DES TECHDAYS 2010!LANCEMENT EN PREVIEW DE CYCLONE LORS DES TECHDAYS 2010! par MPOWARE
Toutes les vidéos de ce lancement sont en ligne!
Partie I - Intro
http://www.youtube.com/watch?v=LkQzTQ8T6CA
Partie II - Démo 1
http://www.youtube.com/watch?v=drAhYQ7lqvo
Partie III - Démo 2
http://www.youtube.com/watch?v=c8KM_1Gqybc...
Cliquez pour lire la suite de l'article par MPOWARE
Logiciels
Academy System (10.9.4.0)ACADEMY SYSTEM (10.9.4.0)Logiciel de gestion des établissements.
- élèves/étudiants (inscription, dossier, absence...)
-... Cliquez pour télécharger Academy System Xilisoft Convertisseur Vidéo Ultimate (5.1.39.0305)XILISOFT CONVERTISSEUR VIDéO ULTIMATE (5.1.39.0305)Xilisoft Convertisseur Vidéo Ultimate est un outil puissant de conversion vidéo, facile à utilise... Cliquez pour télécharger Xilisoft Convertisseur Vidéo Ultimate Xilisoft DVD Ripper Ultimate (5.0.64.0304)XILISOFT DVD RIPPER ULTIMATE (5.0.64.0304)Xilisoft DVD Ripper Ultimate est un logiciel excellent pour copier et convertir DVD vers presque ... Cliquez pour télécharger Xilisoft DVD Ripper Ultimate Rigs of Rods (63.3)RIGS OF RODS (63.3)c'est un jeu de multi-simulation camions,autobus voitures, avions, bateaux, hélicoptère avec défo... Cliquez pour télécharger Rigs of Rods
|