在Windows CE C#程序中访问线程中的控件

时间:2014-03-10 14:03:06

标签: c# compact-framework windows-ce backgroundworker invoke

我正在 C#中编写 WinCE6 程序,使用网络(TCP / IP)和 Serialport 。我使用线程进行套接字侦听,并且我希望在表单上的标签中显示收到的数据。 但是在访问线程中的控件时出错,我想用调用 - BeginInvoke 命令来解决它,但是没有用。 BackgroundWorker

if (txtTCPRecieve.InvokeRequired)
{
    SetTextCallback d = new SetTextCallback(SetText);
    txtTCPRecieve.Invoke(d);
}

delegate void SetTextCallback();

void SetText()
{
    label3.Text = stringData;
}

有人可以帮忙吗?

TNX

1 个答案:

答案 0 :(得分:1)

每次我需要从后台线程更新UI元素时,我使用以下代码(此处更新名为&#34的文本框; txtLog":

    delegate void SetTextCallback(string text);
    public void addLog(string text)
    {
        // InvokeRequired required compares the thread ID of the
        // calling thread to the thread ID of the creating thread.
        // If these threads are different, it returns true.
        if (this.txtLog.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(addLog);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            txtLog.Text += text + "\r\n";
            //scroll to updated text
            txtLog.SelectionLength = 0;
            txtLog.SelectionStart = txtLog.Text.Length - 1;
            txtLog.ScrollToCaret();
        }
    }
相关问题