2017-06-19 83 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