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
PARUTION DE MON LIVRE SUR WPF 4PARUTION DE MON LIVRE SUR WPF 4 par odewit
La 2e édition de mon livre sur WPF sort aujourd'hui en version numérique et lundi en version papier :-)
L'ouvrage présente de façon approfondie les fonctionnalités de WPF 4 : graphisme 2D et 3D, animation, multimédia, interfaces utilisateur, databind...
Cliquez pour lire la suite de l'article par odewit EDM : COMMENT UTILISER L'HORIZONTAL ENTITY SPLITTINGEDM : COMMENT UTILISER L'HORIZONTAL ENTITY SPLITTING par Matthieu MEZIL
Une des raisons pour lesquelles j'adore l'Entity Framework est la puissance de son mapping. Beaucoup de développeurs pour ne pas dire la plus part n'en n'ont pas conscience. Pour rappel, j'ai réalisé des videos (en anglais) sur le mapping . Certains scena...
Cliquez pour lire la suite de l'article par Matthieu MEZIL [WP7DEV][REACTIVE] RENDRE LES REACTIVE EXTENSIONS PLUS STABLES[WP7DEV][REACTIVE] RENDRE LES REACTIVE EXTENSIONS PLUS STABLES par jay
Lorsque l'on développe des applications .NET, les exceptions non gérées dans des threads ont le désagréable effet de terminer le processus courant.
Dans l'exemple suivant.......(read more) ...
Cliquez pour lire la suite de l'article par jay WINDBG / SOS / PSSCOR2 : FAILED TO LOAD DATA ACCESS DLL (MSCORDACWKS)WINDBG / SOS / PSSCOR2 : FAILED TO LOAD DATA ACCESS DLL (MSCORDACWKS) par coq
Ceux d'entre nous qui analysent des dumps d'applications .NET (notamment ceux créés via WER après un crash) en dehors de l'environnement initial ont probablement tous été confrontés au moins une fois au message suivant, à la saisie d'une commande SOS ...
Cliquez pour lire la suite de l'article par coq
Forum
RE : CRéATION DE MODULERE : CRéATION DE MODULE par The Meteorologist
Cliquez pour lire la suite par The Meteorologist
Logiciels
Microsoft Office (2010)MICROSOFT OFFICE (2010)Microsoft Office 2010 offre de nouveaux moyens flexibles et puissants pour optimiser votre travai... Cliquez pour télécharger Microsoft Office SeaMonkey (2.0.7)SEAMONKEY (2.0.7)Le projet SeaMonkey est issu d'un effort communautaire pour developper une application tout en un... Cliquez pour télécharger SeaMonkey Safari (5.0.2)SAFARI (5.0.2)Le navigateur d'Apple a lui aussi été mis à jour, aussi bien dans sa mouture Windows que celle po... Cliquez pour télécharger Safari Mozilla FireFox (4.0 béta 5)MOZILLA FIREFOX (4.0 BéTA 5)Firefox 4.0 béta 5
L'une des nouveautés visibles les plus attendues réside sans doute dans l'a... Cliquez pour télécharger Mozilla FireFox Mozilla Firefox (3.6.9)MOZILLA FIREFOX (3.6.9)Firefox 3.6.9 corrige les problèmes suivants :
* Introduced support for the X-FRAME-OPTION... Cliquez pour télécharger Mozilla Firefox
|