在c#中从线程调用表单控件

本文关键字:调用 表单 控件 线程 | 更新日期: 2023-09-27 18:10:58

我现在陷入了一个很深的问题。请帮帮我....

我创建了一个FORM,命名为form1。它包含一个文本框T1。我启动了它…在form1内部,有一个线程正在运行进程P,它是另一个CLASS的成员,称为class2。要运行进程P,我需要一个来自文本框T1的值。我怎么做呢?

让我告诉你,我已经试过了。我在class2中创建了form1的实例,然后尝试读取文本框(T1)值。但那是空的,我找到了原因....休息,我试过了……再失败…

请帮帮我。我被困了几个小时....

在c#中从线程调用表单控件

这只是为您指明正确方向的一个示例。正如在另一个答案中提到的,您可能必须调用以防止跨线程异常。

在你的类FORM中添加一个方法或属性:

public string GetTextboxContent()
{
    return textbox.Text;
}

class2更改为如下内容:

class class2
{
    private MyForm m_form;
    public class2(MyForm form)
    {
        m_form = form;
    }
    public void DoThreadStuff()
    {
        string value = m_form.GetTextboxContent();
    }
}

你说"我在class2中创建了form1的实例,然后试图读取文本框(T1)值。"不要创建新的实例:将现有的实例传递给class2!

    Assuming Class1 is the class which does some process in thread. Create the property which corresponds to type of your main form. In this case, its called Form1. 

     class Class1
        {
    //his is the property
            public Form1 MyMainForm { get; set; }
            public  void    ShowText()
            {
//here the control is accesses 
//((TextBox)MyMainForm.Controls.Find("textBox1",true)[0])
                MessageBox.Show(((TextBox)MyMainForm.Controls.Find("textBox1",true)[0]).Text);
            }
        }
    im assuming ShowText() method is called on new thread, when button is clicked.
     private void button1_Click(object sender, EventArgs e)
            {
    //craete instance of class1
                Class1 c = new Class1();
    //set the  property            
    c.MyMainForm = this;
    //start the method is new thread
                ThreadStart ts=new ThreadStart(c.ShowText);
                Thread t=new Thread(ts);
                t.Start();
            }

试试这个…

你类. .

ClassText
{
   YourClass(String textVAlue)
   {
   }
 }

表单. .

ClassText ct = new ClassText();
ct.YourClass(Textbox1.text);