超初心者です。
Visual C++ 2008において、Threadによる操作。
<Form1.h>
#pragma once
namespace TextChange {
(中略)
public ref class Form1 : public System::Windows::Forms::Form {
(中略)
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
bool threadStart = true;
this->textBox1->Text = "";
Thread^ thread = gcnew Thread( gcnew ThreadStart(this, &TextChange::Form1::ThreadProc ) );
thread->Start();
while(threadStart==true){
this->button1->Enabled = false;
}
this->button1->Enabled = true;
}
private: void ThreadProc() {
this->textBox1->Text = "検索中";
// DirSearch("C:\\","notepad.exe");
}
}
}
という処理を行っています。
エラーコードは発生しないものの、
「this->textBox1->Text = "検索中";」
の行でフリーズしてしまいます。(ブレイクボイントにより)
パソコンのOSはWindowsXP SP2です。
このコードの何がいけないのか全く分かりません。
良く分かってはいないのですが、同じオブジェクトであるため同期が必要なのでしょうか?
どなたかご教示お願いします。
詳細な説明は@ITに任せるとして
http://www.atmarkit.co.jp/fdotnet/dotnettips/312ctrlinvoke/ctrlinvoke.html
別スレッドからコントロールにアクセスするときはInvokeメソッドを
使わなければならないらしいです。
てな訳でこんなの作ってみた。
private: void ThreadProc() {
SetText("検索中");
// DirSearch("C:\\","notepad.exe");
}
private: void SetText(String ^text) {
if(this->textBox1->InvokeRequired) {
Invoke(gcnew testForm2::Form1::SetTextDelegate(this, &Form1::SetText), text);
} else {
this->textBox1->Text = text;
}
}
private: delegate void SetTextDelegate(String ^text);
プロジェクトやフォームの名前は変わってますよ。
もっとスマートに書けないものかなぁ・・・
追記:
Invokeを呼び出すところは
Invoke(gcnew SetTextDelegate(this, &Form1::SetText), text);
だけでも動いた。
SetTextのForm1::は譲れないらしい。
そだ さん
問題は解決しましたが、Invokeが何であるのかよく分かっていない状態です。
Invokeについてしっかり勉強してみたいと思います。
ありがとうございました。