Controlling form elements from a different thread in Windows Mobile

前端 未结 3 380
庸人自扰
庸人自扰 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-23 16:44

    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);.

提交回复
热议问题