简体   繁体   English

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

[英]How do I access a form's control from another thread?

Using VC++ 2010. 使用VC ++ 2010。

I want to access a form's control from a class in another thread.. and can't figure out the best (or any) way to do this. 我想从另一个线程中的类访问表单的控件..无法找出最佳的(或任何)方法。 How can I pass a reference of my form instance? 如何传递表单实例的引用? Im using createthread() as opposed to the managed version, wanting to make my app compatible with XP. 我使用createthread()而不是托管版本,希望使我的应用程序与XP兼容。

I've tried passing a reference and other values in a struct through the lpParameter, but I can't seem to figure out how to declare the reference properly. 我试图通过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;
}

are giving me errors: 给我错误:

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

FMain is the name of my form class, and I have a delegate method already set up to make it multithread safe: 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;
        }
    }

How do I declare a reference to my form? 如何声明对表格的引用? Or is there an easier or better way to do this? 还是有更简单或更完善的方法来做到这一点?

I don't know what forms library you're using, but the general rule of thumb for your question is, "Don't." 我不知道您使用的是哪种表单库,但一般的经验法则是“不要”。

Unless you have a peculiar GUI library, Windows UI is thread-affinitized. 除非您有一个特殊的GUI库,否则Windows UI是线程关联的。 All access to UI elements should be done via the ui's affinitized thread. 对UI元素的所有访问都应通过ui的关联线程完成。 Manipulating UI state from an unaffinitized execution context should be done by marshaling the update request to the affinitized context. 通过将更新请求编组到关联的上下文中,可以从未关联的执行上下文中操纵UI状态。 It should not be done directly. 它不应该直接完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM