如何从另一个线程访问表单的控件?

时间:2015-10-05 22:30:30

标签: multithreading forms visual-c++ variable-declaration

使用VC ++ 2010。

我想从另一个线程中的类访问表单的控件..并且无法找出执行此操作的最佳(或任何)方法。如何传递表单实例的引用?我使用createthread()而不是托管版本,希望让我的应用程序与XP兼容。

我已经尝试通过lpParameter在结构中传递引用和其他值,但我似乎无法弄清楚如何正确地声明引用。

ref class SZClass {
    private:
        FMain ^bound_form;
        int server_port;
    public:
        void BindForm(FMain ^bf);
        void Initialize(int sp)
}

struct param_data {
    public:
        FMain ^form_tobind;
        int port_num;
}

给我错误:

error C2143: syntax error : missing ';' before '^'

FMain是我的表单类的名称,我已经设置了一个委托方法,使其多线程安全:

public:
    FMain(void)
    {
        InitializeComponent();
        //
        //TODO: Add the constructor code here
        //
    }

    void FMain::PrintConsole(std::string mzg) {
        String ^Smzg = marshal_as<String^>(mzg);
        if (this->textBox1->InvokeRequired) {
            SetTextDelegate^ d =  gcnew SetTextDelegate(this, &FMain::PrintConsole);
            this->Invoke(d, gcnew array<Object^> { Smzg });
        } else {
            textBox1->Text += Smzg;
            textBox1->SelectionStart = textBox1->TextLength;
        }
    }

如何声明对表单的引用? 或者有更简单或更好的方法吗?

1 个答案:

答案 0 :(得分:0)

我不知道您正在使用哪种表格库,但您的问题的一般经验法则是“不要。”

除非您有一个特殊的GUI库,否则Windows UI是线程关联的。所有对UI元素的访问都应该通过ui的affinitized线程完成。应该通过将更新请求编组到关联的上下文来完成从未确定的执行上下文中操纵UI状态。它不应该直接完成。