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
UNE JOLIE-HORLOGE ET PAS QU'UN PEU !UNE JOLIE-HORLOGE ET PAS QU'UN PEU ! par neodante
Pour les possesseurs d'iPhone, ça y est Bijin Tokei - qui se traduit littéralement en Français par " Jolie Horloge " - est arrivé et GRATUITEMENT s'il vous plaît ! Après la version Tokyo, Hokkaido, night club, racing, Gal, "pour les mademoiselles'", . voi...
Cliquez pour lire la suite de l'article par neodante TECHDAYS PARIS 2010 : CONNECTEZ VOS DONNéES à SHAREPOINT 2010 AVEC LES BUSINESS CONNECTIVITY SERVICESTECHDAYS PARIS 2010 : CONNECTEZ VOS DONNéES à SHAREPOINT 2010 AVEC LES BUSINESS CONNECTIVITY SERVICES par ROMELARD Fabrice
Animé par: Gaetan Bouveret et Julien Chomarat Business Connectivity Services (BCS) est dans SharePoint 2010 la version 2 de Business Data Catalog (BDC dans SharePoint 2007). Il s'agit de la solution permettant de visualiser des données provenan...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice [DIVERS] SUIVRE VOS SéRIES PRéFéRéS SUR LA TOILE[DIVERS] SUIVRE VOS SéRIES PRéFéRéS SUR LA TOILE par orion
Comme de nombreux geek, je suis un grand amateur de série TV et je rate régulièrement des épisodes de mes séries préférés. Une solution s'offre à vous avec ce merveilleux site : Tv Gorge - www.tvgorge.com Moteur de recherche à l'appui, vous pouvez ...
Cliquez pour lire la suite de l'article par orion TECHDAYS PARIS 2010 : LA BI DANS SHAREPOINT 2010TECHDAYS PARIS 2010 : LA BI DANS SHAREPOINT 2010 par ROMELARD Fabrice
Animé par: Vincent Bellet et Baptiste Giraudier La BI dans SharePoint 2010, Les nouveaux services d'application dans SP2010 et SQL Server Reporting services 2008 R2. La BI dans SharePoint est généralisée pour tous afin de permettre à tous les coll...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice
Logiciels
DB-MAIN (9.1.0)DB-MAIN (9.1.0)DB-MAIN is a data-modeling and data-architecture tool. It is designed to help developers and anal... Cliquez pour télécharger DB-MAIN Xilisoft DPG Convertisseur (5.1.37.0120)XILISOFT DPG CONVERTISSEUR (5.1.37.0120)Xilisoft DPG Convertisseur offre aux fans de Nintendo DS une bonne solution leur permettant de dé... Cliquez pour télécharger Xilisoft DPG Convertisseur GraphicsGale (2.01.01)GRAPHICSGALE (2.01.01)GraphicsGale est un logiciel de PixelArt avec de nombreuse fonctionnalités permettant de réalisé ... Cliquez pour télécharger GraphicsGale Architecte 3D (Platinum 2010)ARCHITECTE 3D (PLATINUM 2010)Architecte 3D Platinium vous permet de concevoir facilement les plans votre future maison, de l'é... Cliquez pour télécharger Architecte 3D TeamViewer 5 (TeamViewer 5)TEAMVIEWER 5 (TEAMVIEWER 5)Dépanner un ami,expliquer une manipulation devient un jeu d'enfant.
Prise en main d'un autre ord... Cliquez pour télécharger TeamViewer 5
|