smithvoice.com
 Y'herd thisun? 

“There is nothing inherently expensive about rockets. It's just that those who have built and operated them in the past have done so with horrendously poor efficiency.”
-Elon Musk



Winform Designmode

TaggedCoding, CSharp, DotNet

Coding out and about without my libraries drive and hit that old, old, old bug of user controls not making it easy to tell you when you're in Designmode if you nest subclassed UCs. Felt like a noob fool, had to waste time running through all of the forum posts of hacks that still don't work.. till I found this one. It's not mine but it's better than mine in that it works (for me) across the nesting scenarios even when called from a grandchild control.  Now I'm glad I forgot my drive :).

The code is in an Anonymous comment, in case that page goes away, I put it here.

Why does the simple DesignMode feature that was spot-on in the VB5/6 era still elude the VS team after ten years of .Net?

Thanks Anonymous!

        //optional for caching value
        private bool _isRuntime = false;

protected override void OnHandleCreated(EventArgs e)
        {
            base.OnHandleCreated(e);
            _isRuntime = Runtime();
            //if (RunTime())
            // use this positive result and call your control data/initialization here instead of cstor
            //MessageBox.Show("RunTime", (this.Name + " " + this.GetType().Name).Trim());
            //else
            //MessageBox.Show("DesignTime", (this.Name + " " + this.GetType().Name).Trim());
        }

private bool RunTime()
        {
            Form parentForm = this.FindForm();
            Control parentControl = this.Parent;
            // Start with highest level and work down.
            if (parentForm != null)
                if (parentForm.Site != null && parentForm.Site.DesignMode)
                    return false;
                else
                    return true;
            else if (parentControl != null)
            {
                if (parentControl.Site != null && parentControl.Site.DesignMode)
                    return false;
                else
                    return true;
            }
            else if (this.Site != null && this.Site.DesignMode)
                return false;
            else
                return true;
        }

 

Call it whenever or cache the bool or adapt it as a library/utility function passing in the instance.  Seems to fit the designtime rendering bill for my controls that hit services.



home     who is smith    contact smith     rss feed π
Since 1997 a place for my stuff, and it if helps you too then all the better smithvoice.com