【问题标题】:Accessing Controls in a Thread in Windows CE C# Program在 Windows CE C# 程序中访问线程中的控件
【发布时间】:2014-03-10 14:03:06
【问题描述】:

我正在用 C# 为 WinCE6 编写程序,使用 Network (TCP/IP) 和 Serialport。我使用 thread 进行套接字侦听,并且在收到数据时,我想在表单上的 label 中显示它。 但是 accessing 线程中的控件有一个错误,我想用 Invoke - BeginInvoke 命令解决它,但没有奏效。 BackgroundWorker!

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

delegate void SetTextCallback();

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

有没有人可以帮忙?

tnx

【问题讨论】:

  • 显示您的代码。解释“没用”
  • @Alan,“没有工作”意味着程序运行没有任何错误并且工作正常,但是那段代码没有执行,例如标签没有改变! if (txtTCPRecieve.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); txtTCPRecieve.Invoke(d); } delegate void SetTextCallback(); void SetText() { label3.Text = stringData; }
  • 如果在 SetText 方法中设置断点会发生什么?它会被执行吗?
  • 你是要设置 txtTCPRecieve 还是 label3?
  • 看起来基本正确。要么您设置了错误的控件文本,要么您的代码永远不会被您的工作人员调用。 在您的代码中放置断点并单步执行

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


【解决方案1】:

每次我需要从后台线程更新 UI 元素时,我都会使用以下代码(这里更新名为“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();
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多