Controlling form elements from a different thread in Windows Mobile

前端 未结 3 419
庸人自扰
庸人自扰 2021-01-23 16:06

Trying to get a thread to change form controls in Windows Mobile.

Throws an unsupported exception.

Does this mean it cant be done at all?

If not, how do

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-23 16:44

    You need to use the Control.InvokeRequired property as UI elements must be accessed from the main thread.

    In your background thread you raise an event.

    public event EventHandler MyApp_MyEvent;
    
    this.MyApp_MyEvent(this, new MyEventArgs(MyArg));
    

    In you main UI thread you subscribe to that event:

    this.myThread.MyApp_MyEvent+= this.MyAppEventHandler;
    

    and the handler itself:

    private void MyApp_EventHandler(object sender, MyEventArgs e)
    {
        if (this.MyControl.InvokeRequired)
        {
            this.MyControl.Invoke((MethodInvoker)delegate { this.MyAction(e.MyArg); });
        }
        else
        {
            this.MyAction(e.MyArg);
        }
    }
    

提交回复
热议问题