• 締切済み

Visual c# スレッド

プログラム初心者です。 Visual c#にてスレッド関数を使ったプログラムを見よう見まねで 作りました。 スタートボタンを押すとピクチャーボックスの位置が 左から右へ移動し、ストップボタンを押すと止まる。 ピクチャーボックスの位置をテキストボックスに表示する。 というプログラムのつもりです。 デバックの状態でスタートボタンを押すとエラーメッセージが出て テキストボックスに位置を書き込むの関数のところが緑色にハイライトされます。エラーの内容は「有効でないスレッド間の操作」とありますが、どうしたら良いのか分かりません。 エラーの直し方を教えてください。 プログラムコードは以下です。 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading; namespace bit_map_08._1._ { public partial class Form1 : Form { private Thread thread; static private int Position = 0; static private int i; static bool BtnOnFig; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { thread = new System.Threading.Thread(newSystem.Threading.ThreadStart(MainThread)); thread.Start(); } private void PointMove() { if (i < 300) { i = i + 1; Position = Position + i; textBox1.Text = Convert.ToString(Position); pictureBox1.Left = (Position); } if (i == 300) { i = 0; } } private void MainThread() { while( true ) { Thread.Sleep(100); if (BtnOnFig == true) { PointMove(); } } } private void button1_Click(object sender, EventArgs e) { BtnOnFig = true; } private void button2_Click(object sender, EventArgs e) { BtnOnFig = false; } } }

みんなの回答

  • btob
  • ベストアンサー率22% (147/663)
回答No.1

C#のスレッドには詳しくないですが、VC++でも、この方法はプログラムは停止します。コントロールは、スレッドごとの管理になっているので、子スレッドから別スレッド管理下のコントロールを操作すると、存在しないコントロールを操作することになるので、プログラムが飛びます。 VC++で子スレッドから、親スレッド管理下のコントロールを操作するときは、子スレッドから親スレッドにメッセージを送ります。親スレッドは、そのメッセージを受信したら、コントロールを操作するようにさせています。 おそらく、C#でも同じ原因で飛んでいると思いますし、同じ解決方法がとれる思います。 後は、C#に詳しい方にお任せします。

tomasbenso
質問者

お礼

回答ありがとうございます。 このプログラムのスレッドに親と子があることを知りませんでした。 テキストボックスやピクチャーボックスなどツールから選んで フォームに貼り付けるものは自前のスレッド以外のスレッドで 管理されてるのどしょうか? お時間がありましたらVC++の方法でも良いので聞かせてください。 よろしくお願いします。

関連するQ&A

  • C#プログラムにて

    C#プログラムにて お世話になります。 C#初心者です。 プログラムコードを書き始めで、早速行き 詰っています。 ステップでコードの動きを確認したところ、 program.csのMainから下記のForm1.csに 移りForm1のデザイナが表示されるのですが、 button3を押してもForm3が表れません。 また、ステップの黄色いカーソルと言いますか ステップの位置情報も消えています。 何がどう悪いのか分からなく困っています。 どなたかご親切な方、ご教授頂きたく 宜しくお願い致します。     記 using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication3 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void button3_Click(object sender, EventArgs e) { Form3 cForm3 = new Form3(); cForm3.ShowDialog(); } private void button2_Click(object sender, EventArgs e) { DialogResult ans; ans = MessageBox.Show("最新のコード表を照会しますか?", "Microsoft Visual Studio", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (ans == DialogResult.OK) Application.Exit(); } private void button12_Click(object sender, EventArgs e) { Form4 cForm4 = new Form4(); cForm4.ShowDialog(); } } }

  • C#で処理中の状況をStatusLabelに表示

    C#で処理中の状況をStatusLabelに表示させたいのですが、どうやらマルチスレッドを使えば良いらしい事は分かったのですが、説明しているページを参考にいろいろやってみたのですがどうもうまくいきません。 例えば次のような場合、10秒後に”9”と表示されて終わってしまうのですが、どの様に書き直せばよろしいでしょうか? すみません、どなたかご存じの方教えていただけないでしょうか。 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; namespace test_multithread3 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { for (int i = 0; i < 10; i++) { toolStripStatusLabel1.Text = i.ToString(); Thread.Sleep(1000); } } } }

  • BackgroundWorkerについて(C#)

    C#でBackgroundWorkerを使ったプログラムを試しています。 Windows Form上にButtonとProgressBarを設置して以下のプログラムを 動作させると、プログレスバーが終了するまえに”終了”が出てしまいますが これはどうしてでしょうか? よろしくお願いいたします。 using System; using System.ComponentModel; using System.Threading; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { button1.Enabled = false; Random rand = new Random(); BackgroundWorker bgWorker = new BackgroundWorker(); bgWorker.DoWork += ((sender2, e2) => { for (int i = 0; i < 10; i++) { Thread.Sleep((int)(rand.NextDouble() * 500)); bgWorker.ReportProgress((i + 1) * 10); } }); bgWorker.RunWorkerCompleted += ((sender2, e2) => { button1.Enabled = true; bgWorker.Dispose(); MessageBox.Show("終了"); }); bgWorker.ProgressChanged += ((sender2, e2) => { progressBar1.Value = e2.ProgressPercentage; }); bgWorker.WorkerReportsProgress = true; bgWorker.RunWorkerAsync(); } } }

  • C# フォームを閉じてもプログラムが終了しない

    前略 ・C#の初心者です。 ・下記のようなプログラムを作りたいと思っています。プログラムは<作りたいプログラム>の仕様どうりに動作していますが、Form1のFormClosingイベントに Application.Exit()を追加しないと フォーム1で "X"(閉じる)をクリックしても(フォームは非表示になりますが)プログラムが終了しません。プログラムでどこかおかしな部分があると思っています。Application.Exit()を追加しないでもプログラムを終了する方法を教えてください。 <作りたいプログラム> (1)Form1 のbutton1をクリックすると新しいForm2が作成され表示される。Form2が表示されるとForm1は非表示となる。 (2)Form2 のbutton1をクリックするとForm2が非表示となりForm1が表示される。 (3)Form1 の "X"(閉じる)をクリックしてプログラムを終了する。 //Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace formClose { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Form2 form2 = new Form2(); form2.Show(); //フォーム2を表示 this.Hide(); //フォーム1を非表示 } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { Application.Exit(); //アプリケーション終了 } } } //Form2.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace formClose { public partial class Form2 : Form { Form1 form1 = new Form1(); public Form2() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { this.Close(); //フォーム2を閉じる } private void Form2_FormClosing(object sender, FormClosingEventArgs e) { form1.Show(); //フォーム1を表示する } } } 以上

  • C# 簡単なシューティング 自機移動について

    かなりの初心者で困っています。 簡単なシューティングを作ろうとおもっています。 使用ソフトはVisualC#2005です。 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //自機(右移動) private void button3_Click(object sender, EventArgs e) { if (timer1.Enabled == false) { timer2.Enabled = false; timer1.Enabled = true; } else { timer1.Enabled = false; timer3.Enabled = false; timer4.Enabled = false; } } private void timer1_Tick(object sender, EventArgs e) { pictureBox1.Left = pictureBox1.Left + 2; } //自機(左) private void button4_Click(object sender, EventArgs e) { if (timer2.Enabled == false) { timer1.Enabled = false; timer2.Enabled = true; } else { timer2.Enabled = false; timer3.Enabled = false; timer4.Enabled = false; } } private void timer2_Tick(object sender, EventArgs e) { pictureBox1.Left = pictureBox1.Left - 2; } //自機(上) private void button1_Click(object sender, EventArgs e) { if (timer3.Enabled == false) { timer4.Enabled = false; timer3.Enabled = true; } else { timer1.Enabled = false; timer2.Enabled = false; timer3.Enabled = false; } } private void timer3_Tick(object sender, EventArgs e) { pictureBox1.Top = pictureBox1.Top - 2; } //自機(下) private void button2_Click(object sender, EventArgs e) { if (timer4.Enabled == false) { timer3.Enabled = false; timer4.Enabled = true; } else { timer1.Enabled = false; timer2.Enabled = false; timer4.Enabled = false; } } private void timer4_Tick(object sender, EventArgs e) { pictureBox1.Top = pictureBox1.Top + 2; } } } 自機は画像(PictureBox)でボタンによって上下左右に移動します。 FormのSizeは800,630です。 自機の移動がボタンなのでキー入力によって操作できるようにしたいのですが、 それと、自機の移動範囲を画面からでないようにしたいです。 あまりC#を理解できてない上でつくったのでおかしな点が多々あると思います。 教えていただける方がいると助かります。

  • VC# 追加フォーム生成時、フォームに描画できない

    前略 ・VC#(.NET 2008)のプログラムでおしえてください。 ・メインのWindowsフォームからボタンクリックで 追加したサブWindowsフォーム上のピクチャーボックス上に何も操作なしでに描画したいのですができません。CreateGraphics()でオブジェクトを生成して描画しています。どのようにしたらよいのかおしえてください。フォームのイベントとして、Paint,Load,shown,Activated等いろいろやってもだめでした。  尚、サブフォームにボタンをもうけ このメソッドの中に描画コマンドを書き、ボタンを操作すると描画できます。下記は円を描こうとしていますが、shapeコンポーネントでは描けな複雑な描画をしたいと思っています。 ・以下に 下記の動作となるソースコードを記載します。 (1)起動するとメインフォームForm1のpictureBox1に 赤い円が描かれる (2)ボタンbutton1をクリックするとForm2が表示される。  Form2上のラベルlabel1とlabel2の文字色は青色に変わっています。  しかし、円は何故か描かれていません (3)Form2上のボタンをクリックすると赤い円がForm2上に描かれます。  どこをどのように直せば追加のサブフォームForm2が表示された時に Form2上のpictureBox1に円が描がかれているのでしょうか。以上、よろしくお願いします //----------------------------------------------------------- //メインフォーム using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace temp2 { public partial class Form1 : Form { public Form1(){ InitializeComponent(); } private void button1_Click(object sender, EventArgs e){ Form2 form2 = new Form2(); form2.ShowDialog(); } private void Form1_Paint(object sender, PaintEventArgs e){ Graphics g = pictureBox1.CreateGraphics(); g.DrawEllipse(Pens.Red, 0, 0, 200, 200); } } } //サブフォーム using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace temp2 { public partial class Form2 : Form { public Form2(){ InitializeComponent(); } private void pictureBox1_Paint(object sender, PaintEventArgs e){ label1.ForeColor = Color.Blue; Graphics g1 = pictureBox1.CreateGraphics(); g1.DrawEllipse(Pens.Blue, 0, 0, 50, 50); label2.ForeColor = Color.Blue; } private void button1_Click(object sender, EventArgs e){ Graphics g2 = pictureBox1.CreateGraphics(); g2.DrawEllipse(Pens.Blue, 0, 0, 50, 50); } private void Form2_Paint(object sender, PaintEventArgs e){ } private void Form2_Load(object sender, EventArgs e){ } private void Form2_Shown(object sender, EventArgs e){ } } } 以上

  • C#での時間制限のプログラム

    C#初心者です。Visual studioでプログラムを書いてます。 ラベルに制限時間を表示させ、起動して30秒経つと 「もういちどやりますか?」というメッセージボックスが出て、 「はい」でもう一度開始、「いいえ」でプログラムを終了させるような 処理をさせたいのですが、「はい」を押しても同じメッセージボックスが出てループしてしまい、もう一度開始させることができません…。 解決する方法を教えていただきたいです。よろしくお願いします。 以下、書いたコードです。 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace timelimit { public partial class Form1 : Form { public Form1() { InitializeComponent(); } DateTime StartTime; TimeSpan TimeLimit; private void Form1_Load(object sender, EventArgs e) { timer1.Enabled = true; StartTime = DateTime.Now; TimeLimit = new TimeSpan(0,0,30); } private void timer1_Tick(object sender, EventArgs e) { TimeSpan tm = DateTime.Now - StartTime; if(tm > TimeLimit) { TimeLimit = new TimeSpan(0, 0, 30); timer1.Enabled = false; DialogResult result = MessageBox.Show ("時間終了!もういちどやりますか?","終了処理",MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { timer1.Enabled = true; } else if (result == DialogResult.No) { Close(); } }else{ label1.Text = (TimeLimit - tm).ToString(); } }

  • 別スレッドからメインスレッドのテキストボックスに文字を表示させたい

    Visual C++ 2005 Express Editionを使用している初心者です。 タイトルの方法がどうしてもわからないので教えてください。 うまく説明できないので聞きたいところのコードを載せます。 //SAMPLE.cpp #include "stdafx.h" #include "Form1.h" using namespace SAMPLE; int main(array<System::String ^> ^args) { Application::EnableVisualStyles(); Application::SetCompatibleTextRenderingDefault(false); Application::Run(gcnew Form1()); } //Form1.h #include <process.h> #include <vcclr.h> namespace SAMPLE { unsigned __stdcall counter(void *arg); int thread_id1; unsigned dummy; using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; public ref class Form1 : public System::Windows::Forms::Form { public:Form1(void) { InitializeComponent(); //別スレッド起動 thread_id1=_beginthreadex(NULL,0,counter,(void *)1,0,&dummy); } private: System::Windows::Forms::TextBox^ textBox1; private: System::ComponentModel::Container ^components; void InitializeComponent(void) { this->textBox1 = (gcnew System::Windows::Forms::TextBox()); //省略(コンポーネント初期化) } private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) { } }; unsigned __stdcall counter(void *arg){ //別スレッド //ここで文字列を記述して上のtextBox1に表示したい return 0; } } 初歩的なことかもしれませんが、 よろしくお願いします。

  • C# フォーム追加後、旧フォームを閉じたい

    前略 ・C#で教えてください。 ・Form1 からshowDiag()メソッドでForm2をつくります。Form2が表示されたら非アクティブとなったForm1を閉じたいのですが どのようにしたらよいのかおしえてください。  下記は、Close() メソッドで Form2側から閉じようとしたプログラムですがFrom1を閉じることができません。 よろしくお願いします。 //----------------------------------------------- namespace formClose { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Form2 form2 = new Form2(); form2.ShowDialog(); } }   public partial class Form2 : Form { public Form2() { InitializeComponent(); } private void Form2_Load(object sender, EventArgs e) { Form1 form1 = new Form1(); form1.Close(); //Form1が閉じない!! } private void button1_Click(object sender, EventArgs e) { this.Close(); //Form2を閉じる }    } } 以上

  • C#で、ある条件でFormが自動で閉じるプログラム

    C#で、例えばForm2をForm1から開き、ある問題があってForm2のボタンを押すとForm2のラベルに正解と表示されます。 その文字が表示されたら数秒後に自動でForm2が閉じられるプログラムを書きたいのですがうまくいきません。 現在、こう書いています。3秒後とします。 using System.Threading;は宣言しています。 private void Form2_FormClosing(object sender, FormClosingEventArgs e) { if(label1.Text=="正解です。") { Thread.Sleep(3000); e.Cancel= false; } こうするといつまでも閉じてくれません。 ボタンクリックプログラムに、if文で、~ならば正解です、~ならば間違いです、などとふり分けている中、正解のところに label1.Text="正解です。"; Thread.Sleep(3000); this.Close(); などとすると、ボタンを押したら、ラベルには何も表示されずに3秒後に閉じます。 どうすればいいでしょうか?