Saturday, September 21, 2013

C#: Safely set the Enabled of the Control across threads.


        /// <summary>
        ///     Safely set the <see cref="Control.Enabled"/> of the control across threads.
        /// </summary>
        /// <param name="control"></param>
        /// <param name="value"></param>
        public static void Enabled( this Control control, Boolean value ) {
            if ( null == control ) {
                return;
            }
            if ( control.InvokeRequired ) {
                control.BeginInvoke( new Action( () => {
                    if ( control.IsDisposed ) {
                        return;
                    }
                    control.Enabled = value;
                    control.Refresh();
                } ) );
            }
            else {
                control.Enabled = value;
                control.Refresh();
            }
        }

No comments: