簡體   English   中英

C#TextBox控件未使用新文本進行更新

[英]C# TextBox Control Not Updating With New Text

我是安全關鍵系統的嵌入式系統軟件開發人員,因此我對C#相當陌生,但是精通基於C的語言。

為了提供一些背景知識,我開發了Windows窗體,該窗體將從嵌入式軟件通過串行端口發送的串行數據包解釋為有意義的調試信息。

我想做的是在TextBox控件中顯示每個數據包的每個字節。 顯示數據包信息的文本框控件實際上是第一個窗體打開的第二個窗體。 這是事件處理程序的代碼,該代碼從第一個表單打開第二個表單:

private void ShowRawSerialData(object sender, EventArgs e)
{
    SendSerialDataToForm = true;
    if (SerialStreamDataForm == null)
        SerialStreamDataForm = new RawSerialDataForm();
    SerialStreamDataForm.Instance.Show();
}

在上面的代碼中,.Instance.Show()偽指令是一種方法,如果關閉了表單,我可以打開新表單,但是如果表單已經打開,則不顯示新表單。 然后,在我的串行數據接收事件處理程序中,執行以下操作:

// Get bytes from the serial stream
bytesToRead = IFDSerialPort.BytesToRead;
MsgByteArray = new Byte[bytesToRead];
bytesRead = IFDSerialPort.Read(MsgByteArray, 0, bytesToRead);
// Now MsgByteArray has the bytes read from the serial stream,
// send to raw serial form
if (SendSerialDataToForm == true && SerialStreamDataForm != null)
{
    SerialStreamDataForm.UpdateSerialDataStream(MsgByteArray);
}

其中MsgByteArray是接收到的串行數據包的字節數組。 這是UpdateSerialDataStream的代碼:

public void UpdateSerialDataStream(Byte[] byteArray)
{
    String currentByteString = null;
    currentByteString = BitConverter.ToString(byteArray);
    currentByteString = "0x" + currentByteString.Replace("-", " 0x") + " ";
    if (RawSerialStreamTextBox.InvokeRequired)
    {
        RawSerialStreamTextBox.Invoke(new SerialTextBoxDelegate(this.UpdateSerialDataStream), new object[] { byteArray });
    }
    else
    {
        RawSerialStreamTextBox.Text += currentByteString;
    }
    RawSerialStreamTextBox.Update();
}

最終結果是用我打算添加到文本框中的字符串正確更新了RawSerialStreamTextBox.Text的值! 例如,如果我傳遞字節數組{0x01,0x7F,0x7E},那么通過調試器,我可以看到RawSerialStreamTextBox.Text的值=“ 0x01 0x7F 0x7E”。

問題是文本框控件本身不顯示新添加的文本。 因此,即使我可以通過調試器確認RawSerialStreamTextBox.Text =“ 0x01 0x7F 0x7E”,Windows中的文本框也不顯示“ 0x01 0x7F 0x7E”,而是保持空白。

關於這里可能發生什么的任何想法?

我猜您是在一個實例上設置Text屬性,而不是實際顯示的實例。 健全性檢查將類似於

RawSerialStreamTextBox.Visible = false;

它消失了嗎?

為了簡單起見,我將讓UpdateSerialDataStream返回一個字符串(或將一個字符串傳遞給out參數),以便事件處理程序看起來像這樣:

    // Get bytes from the serial stream
    bytesToRead = IFDSerialPort.BytesToRead;
    MsgByteArray = new Byte[bytesToRead];
    bytesRead = IFDSerialPort.Read(MsgByteArray, 0, bytesToRead);
    // Now MsgByteArray has the bytes read from the serial stream,
    // send to raw serial form
    if (SendSerialDataToForm == true && SerialStreamDataForm != null)
    {
        RawSerialStreamTextBox.Text = UpdateSerialDataStream(MsgByteArray);
    }

並且UpdateSerialDataStream看起來像這樣:

public string UpdateSerialDataStream(Byte[] byteArray)
{
    String currentByteString = null;
    currentByteString = BitConverter.ToString(byteArray);
    currentByteString = "0x" + currentByteString.Replace("-", " 0x") + " ";
    return currentByteString;
}

您必須將處理表單顯示的代碼稍微移動一下,但這將允許已經包含TextBox的表單自行處理更新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM