2012-02-19 67 views
1

我想知道是否有人可以幫我解決我遇到的一個小問題。我試圖從另一個類更新文本框,但是文本沒有顯示在文本框中,即使它正在發送,因爲我已將它打印到屏幕上。C#在更新文本框時無法看到文本

我正在使用的代碼如下:

的Program.cs

namespace Search 
{ 
    static class Program 
    { 
     /// <summary> 
     /// The main entry point for the application. 
     /// </summary> 
     [STAThread] 

     static void Main() 
     { 
      Application.EnableVisualStyles(); 

      try 
      { 
       Application.SetCompatibleTextRenderingDefault(false); 
      } 
      catch (InvalidOperationException e) 
      { 

      } 
      Application.Run(new Form1()); 
     } 

     public static readonly Form1 MainLogWindow = new Form1(); 
    } 
} 

HexToASCII:

public class HexToASCII 
{ 
    Output o = new Output(); 

    public void hexToAscii(String hex, int textBox) 
    { 
     //Convert the string of HEX to ASCII 
     StringBuilder sb = new StringBuilder(); 

     for (int i = 0; i < hex.Length; i += 2) 
     { 
      string hs = hex.Substring(i, 2); 
      sb.Append(Convert.ToChar(Convert.ToUInt32(hs, 16))); 
     } 
     //Pass the string to be output 
     string convertedHex = sb.ToString(); 

     Program.MainLogWindow.UpdateTextBox(convertedHex);  
    } 
} 

Form1中:

private delegate void NameCallBack(string varText); 
    public void UpdateTextBox(string input) 
    { 
     if (InvokeRequired) 
     { 
      textBox2.BeginInvoke(new NameCallBack(UpdateTextBox), new object[] { input }); 
     } 
     else 
     { 
      textBox2.Text = textBox2.Text + Environment.NewLine + input; 
     } 
    } 

我試圖運行它使用一個新的線程ThreadStar ts =委託()...但我無法獲取文本框更新。對不起,我對c#很陌生,有人能解釋一下這個問題,所以我可以理解它,並在下次學習。非常感謝:)

+0

刷新文本框中的值設置後 – Beatles1692 2012-02-19 19:05:39

+0

看起來你有Form1'的'兩個完全獨立的實例。嘗試下面,而不是'Application.Run(新的Form1())''寫'Application.Run(Program.MainLogWindow);' – sll 2012-02-19 19:06:52

回答

4

這就是問題所在:

static void Main() 
{ 
    ... 
    Application.Run(new Form1()); 
} 

public static readonly Form1 MainLogWindow = new Form1(); 

你正在創建兩種形式:其中一個正在顯示(與Application.Run),但你改變對文本框的內容另外一個:

Program.MainLogWindow.UpdateTextBox(convertedHex); 

如何你在第一時間致電hexToAscii您還沒有表現出 - 個人而言,我會盡量避免到GUI元素這樣的靜態引用,但你可以得到您代碼來改變你的Main方法只使用工作:

Application.Run(MainLogWindow); 
+0

我錯過了:)) – Beatles1692 2012-02-19 19:08:20

+0

哈哈,現在你已經指出這對我來說是相當顯而易見和一個愚蠢的錯誤!傻新手!非常感謝,但似乎已經解決了這個問題,我會標記你是正確的,當它讓我:) – James 2012-02-19 19:13:26