1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
Fichier form1.h:
----------------
namespace tstThread {
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
myDelegate = gcnew Ecrire(this, &Form1::writeTextBox);
}
private:
delegate void Ecrire(); //la "fonction" déléguée
Ecrire^ myDelegate; //une référence sur la fonction déléguée
//Gestion du bouton Exit
private: System::Void btnExit_Click(System::Object^ sender, System::EventArgs^ e) {
Application::Exit();
}
//Gestion du bouton Start
private: System::Void btnStart_Click(System::Object^ sender, System::EventArgs^ e) {
threadClass^ myThread = gcnew threadClass(this); //passe une référence sur Form1
Thread^ InstanceCaller = gcnew Thread(gcnew ThreadStart(myThread, &threadClass::Run));
// Start the thread.
InstanceCaller->Start();
}
private: void ThreadFunction() {
System::Windows::Forms::MessageBox::Show("ThreadFunction");
threadClass^ myThreadClassObject = gcnew threadClass(this);
myThreadClassObject->Run();
}
/* méthode exécutée par le délégué */
public: void writeTextBox() {
this->textBox1->Text = "Hello";
}
};
}
Fichier threadClass.h:
----------------------
ref class threadClass
{
private:
System::Windows::Forms::Form^ mainForm;
public:
threadClass(Form^);
void Run();
};
Fichier threadClass.cpp:
------------------------
#include "threadClass.h"
threadClass::threadClass(Form^ f)
{
mainForm = f;
}
void threadClass::Run()
{
if(mainForm->InvokeRequired)
System::Windows::Forms::MessageBox::Show("threadClass::InvokeRequired = true");
else System::Windows::Forms::MessageBox::Show("threadClass::InvokeRequired = false");
mainForm->Invoke(mainForm->myDelegate);
} |