2017-06-19 79 views
-1

我有,我需要在一个线程的形式运行中更新的文本,但不能工作究竟如何,这将是acheivable的问题,这是我现有的代码:更新文本从另一个

public partial class Class1: Form 
{ 
    LoadText = loadText; 
    ResourceName = resourceName; 

    static private void ShowForm() 
    { 
     LoadForm = new Class1(LoadText, ResourceName); 
     Application.Run(LoadForm); 
    } 

    static public void ShowLoadScreen(string sText, string sResource) 
    { 
     LoadText = sText; 
     ResourceName = sResource; 

     Thread thread = new Thread(new ThreadStart(Class1.ShowForm)); 
     thread.IsBackground = true; 
     thread.SetApartmentState(ApartmentState.STA); 
     thread.Start(); 
    } 
} 

现在我需要改变在新开工的形式下一个文本框中的文本,这需要从理论“的Class2”执行:

class Class2 
{ 
    public void UpdateThreadFormTextbox 
    { 
     Class1.ShowLoadScreen("text", "text"); 
     //Change textbox in the thread instance of Class1 form 
    } 
} 

我已经研究过使用“调用”,但我不能使用从Class2中,确实有一个解决方案,使我能够更新Class1线程实例fr中的文本om Class2?

+0

Ed以显示全局变量。 –

+1

上面的代码不正确,LoadText和ResourceName是什么类型,UpdateThreadFormtextbox也是一个方法,但没有括号括号。 – ColinM

回答

2

只需使用Invoke从1类:

public partial class Class1: Form 
{ 
    private static Class1 LoadForm; 

    static private void ShowForm() 
    { 
     LoadForm = new Class1(LoadText, ResourceName); 
     Application.Run(LoadForm); 
    } 

    static public void ShowLoadScreen(string sText, string sResource) 
    { 
     LoadText = sText; 
     ResourceName = sResource; 

     Thread thread = new Thread(new ThreadStart(Class1.ShowForm)); 
     thread.IsBackground = true; 
     thread.SetApartmentState(ApartmentState.STA); 
     thread.Start(); 
    } 

    public static void SetText(string text) 
    { 
     Class1.LoadForm.textBox1.Invoke(new Action(() => Class1.LoadForm.textBox1.Text = text)); 
    } 
} 

然后使用从Class2中那个方法:

class Class2 
{ 
    public void UpdateThreadFormTextbox 
    { 
     Class1.ShowLoadScreen("text", "text"); 
     Class1.SetText("TEXT"); 
    } 
} 
+0

谢谢,但以这种方式调用SetText方法SetText必须是静态的,这意味着它不能访问表单实例的标签/文本框......或者我错过了什么? –

+0

'SetText'不是静态的,如果它是静态的,则不能访问'textBox1'。 – ColinM

+0

好的,对不起。得到了错误。用TextBox加载表单? –

1

您也可以通过将文本框的实例来你UpdateThreadFormTextBox方法实现这一目标并致电Invoke从您的Class2

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 
     // Create instance of Class2 
     Class2 secondClass = new Class2(); 
     // Create a new thread, call 'UpdateThreadFormTextbox' 
     // and pass in the instance to our textBox1, start thread 
     new Thread(() => secondClass.UpdateThreadFormTextbox(textBox1)).Start(); 
    } 
} 

public class Class2 
{ 
    public void UpdateThreadFormTextbox(TextBox textBox) 
    { 
     textBox.Invoke(new Action(() => textBox.Text = "Set from another Thread")); 
    } 
} 
+1

这不起作用。它没有考虑到实例化的订单类。第一个实例是Class2类型,它调用Class1的静态方法'ShowLoadScreen',然后创建它自己的一个实例。你的代码正在做其他的事情 –

+0

这是真的,我会留下这个作为一个例子,欧普希望重构他们的代码。 – ColinM