C#中在线程中访问主Form控件的问题

翻译|其它|编辑:郝浩|2007-08-13 10:36:09.000|阅读 1230 次

概述:

# 界面/图表报表/文档/IDE等千款热门软控件火热销售中 >>

 C#不允许直接从线程中访问Form里的控件,比如希望在线程里修改Form里的一个TextBox的内容等等,唯一的做法是使用Invoke方法,下面是一个MSDN里的Example,很说明问题: 

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;

   
public class MyFormControl : Form
   
...{
      
public delegate void AddListItem(String myString);
      
public AddListItem myDelegate;
      
private Button myButton;
      
private Thread myThread;
      
private ListBox myListBox;
      
public MyFormControl()
      
...{
         myButton = 
new Button();
         myListBox = 
new ListBox();
         myButton.Location = 
new Point(72, 160);
         myButton.Size = 
new Size(152, 32);
         myButton.TabIndex = 1;
         myButton.Text = "Add items in list box";
         myButton.Click += 
new EventHandler(Button_Click);
         myListBox.Location = 
new Point(48, 32);
         myListBox.Name = "myListBox";
         myListBox.Size = 
new Size(200, 95);
         myListBox.TabIndex = 2;
         ClientSize = 
new Size(292, 273);
         Controls.AddRange(
new Control[] ...{myListBox,myButton});
         Text = " 'Control_Invoke' example ";
         myDelegate = 
new AddListItem(AddListItemMethod);
      }
      
static void Main()
      
...{
         MyFormControl myForm = 
new MyFormControl();
         myForm.ShowDialog();
      }
      
public void AddListItemMethod(String myString)
      
...{
            myListBox.Items.Add(myString);
      }
      
private void Button_Click(object sender, EventArgs e)
      
...{
         myThread = 
new Thread(new ThreadStart(ThreadFunction));
         myThread.Start();
      }
      
private void ThreadFunction()
      
...{
         MyThreadClass myThreadClassObject  = 
new MyThreadClass(this);
         myThreadClassObject.Run();
      }
   }
   
public class MyThreadClass
   
...{
      MyFormControl myFormControl1;
      
public MyThreadClass(MyFormControl myForm)
      
...{
         myFormControl1 = myForm;
      }
      String myString;

      
public void Run()
      
...{


         
for (int i = 1; i <= 5; i++)
         
...{
            myString = "Step number " + i.ToString() + " executed";
            Thread.Sleep(400);
            
// Execute the specified delegate on the thread that owns
            // 'myFormControl1' control's underlying window handle with
            // the specified list of arguments.
            myFormControl1.Invoke(myFormControl1.myDelegate,
                                   
new Object[] ...{myString});
         }
      }
   }


标签:

本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至chenjj@evget.com

文章转载自:csdn

为你推荐

  • 推荐视频
  • 推荐活动
  • 推荐产品
  • 推荐文章
  • 慧都慧问
扫码咨询


添加微信 立即咨询

电话咨询

客服热线
023-68661681

TOP