Controlling form elements from a different thread in Windows Mobile

荒凉一梦 提交于 2019-12-02 06:52:51

You cannot access GUI items on a non-GUI thread. You will need to determine if an invocation is required to the GUI thread. For example (here's some I made earlier):

public delegate void SetEnabledStateCallBack(Control control, bool enabled);
public static void SetEnabledState(Control control, bool enabled)
{
    if (control.InvokeRequired)
    {
        SetEnabledStateCallBack d = new SetEnabledStateCallBack(SetEnabledState);
        control.Invoke(d, new object[] { control, enabled });
    }
    else
    {
        control.Enabled = enabled;
    }
}

Or

public delegate void AddListViewItemCallBack(ListView control, ListViewItem item);
public static void AddListViewItem(ListView control, ListViewItem item)
{
    if (control.InvokeRequired)
    {
        AddListViewItemCallBack d = new AddListViewItemCallBack(AddListViewItem);
        control.Invoke(d, new object[] { control, item });
    }
    else
    {
        control.Items.Add(item);
    }
}

You can then set the enabled property (from my first example) using ClassName.SetEnabledState(this, true);.

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<MyEventArgs> 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);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!