简体   繁体   中英

Invoking control from a different thread fails with a cross-threading exception

In a windows forms project i have subscribed to global keyboard event using win32 api to fire an event when i press win + alt + E, in the event handler i have this code:

    _rectangle = new ScreenBoundingRectangle();
    _rectangle.Location = Location;
    _rectangle.Visible = true;

i keep a variable to my rectangle, now based on some logic, i want to hide the rectangle so i set the visibility to false using this line of code:

    _rectangle.Visible = false;

However i get the famous cross threading exception, even if i try this :

this.Invoke(new MethodInvoker(() =>
    {
        _rectangle.Visible = false;
    }));

i still get the cross threading exception!

the _rectangle does not have invoke method, is there is any other way around this ?

just for anyone who would use the VisualUIAVerify library and would face this issue:

download the open source and add this to the Visiable property of the ScreenBoundingRectangle

        public bool Visible
        {
            get { return this._visible; }
            set
            {
                this._visible = value;

                if (value)
                    SafeNativeMethods.ShowWindow(_form.Handle, 8);
                else
                {
                    //Here invoke _form:
                    this._form.Invoke(new MethodInvoker(() =>
                    {
                        _form.Hide();
                    }));

                }
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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