File: winforms\Managed\System\WinForms\Control.cs
Project: ndp\fx\src\System.Windows.Forms.csproj (System.Windows.Forms)
#define DEBUG_PREFERREDSIZE
 
//------------------------------------------------------------------------------
// <copyright file="Control.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
 
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Control+ActiveXFontMarshaler..ctor()")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope="member", Target="System.Windows.Forms.Control.PreProcessControlMessageInternal(System.Windows.Forms.Control, System.Windows.Forms.Message):System.Windows.Forms.PreProcessControlState")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope="member", Target="System.Windows.Forms.Control.OnPreviewKeyDown(System.Windows.Forms.PreviewKeyDownEventArgs):System.Void")]
 
/*
 */
namespace System.Windows.Forms {
    using Accessibility;
    using Microsoft.Win32;
    using System;
    using System.Collections;
    using System.Collections.Specialized;
    using System.ComponentModel;
    using System.ComponentModel.Design;
    using System.ComponentModel.Design.Serialization;
    using System.Configuration.Assemblies;
    using System.Diagnostics;
    using System.Diagnostics.CodeAnalysis;
    using System.Diagnostics.Contracts;
    using System.Drawing;
    using System.Drawing.Drawing2D;
    using System.Globalization;
    using System.Security.Permissions;
    using System.Security;
    using System.IO;
    using System.Reflection;
    using System.Runtime.InteropServices;
    using System.Runtime.InteropServices.ComTypes;
    using System.Runtime.Remoting;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Text;
    using System.Threading;
    using System.Windows.Forms.Design;
    using System.Windows.Forms.Internal;
    using Encoding = System.Text.Encoding;
    using System.Drawing.Imaging;
    using System.Windows.Forms.Layout;
    using System.Runtime.Versioning;
    using Automation;
 
    using IComDataObject = System.Runtime.InteropServices.ComTypes.IDataObject;
    using Collections.Generic;
 
    /// <include file='doc\Control.uex' path='docs/doc[@for="Control"]/*' />
    /// <devdoc>
    ///    <para>Defines the base class for controls, which are components
    ///       with visual representation.</para>
    /// </devdoc>
    [
    ComVisible(true),
    ClassInterface(ClassInterfaceType.AutoDispatch),
    DefaultProperty("Text"),
    DefaultEvent("Click"),
    Designer("System.Windows.Forms.Design.ControlDesigner, " + AssemblyRef.SystemDesign),
    DesignerSerializer("System.Windows.Forms.Design.ControlCodeDomSerializer, " + AssemblyRef.SystemDesign, "System.ComponentModel.Design.Serialization.CodeDomSerializer, " + AssemblyRef.SystemDesign),
    ToolboxItemFilter("System.Windows.Forms")
    ]
    public partial class Control :
    Component,
    UnsafeNativeMethods.IOleControl,
    UnsafeNativeMethods.IOleObject,
    UnsafeNativeMethods.IOleInPlaceObject,
    UnsafeNativeMethods.IOleInPlaceActiveObject,
    UnsafeNativeMethods.IOleWindow,
    UnsafeNativeMethods.IViewObject,
    UnsafeNativeMethods.IViewObject2,
    UnsafeNativeMethods.IPersist,
    UnsafeNativeMethods.IPersistStreamInit,
    UnsafeNativeMethods.IPersistPropertyBag,
    UnsafeNativeMethods.IPersistStorage,
    UnsafeNativeMethods.IQuickActivate,
    ISupportOleDropSource,
    IDropTarget,
    ISynchronizeInvoke,
    IWin32Window,
    IArrangedElement,
    IBindableComponent,
    IKeyboardToolTip {
 
#if FINALIZATION_WATCH
        static readonly TraceSwitch ControlFinalization = new TraceSwitch("ControlFinalization", "Tracks the creation and destruction of finalization");
        internal static string GetAllocationStack() {
            if (ControlFinalization.TraceVerbose) {
                // SECREVIEW: This assert is safe, the operation is safe (data obtained from the CLR). This code is for debugging purposes only.
                // Tracked by VSWhidbey #426446.
                new EnvironmentPermission(PermissionState.Unrestricted).Assert();
                try {
                    return Environment.StackTrace;
                }
                    finally {
                        CodeAccessPermission.RevertAssert();
                    }
                }
            else {
                return "Enable 'ControlFinalization' switch to see stack of allocation";
            }
 
        }
        private string allocationSite = Control.GetAllocationStack();
#endif
 
#if DEBUG
        internal static readonly TraceSwitch PaletteTracing = new TraceSwitch("PaletteTracing", "Debug Palette code");
        internal static readonly TraceSwitch ControlKeyboardRouting = new TraceSwitch("ControlKeyboardRouting", "Debug Keyboard routing for controls");
        internal static readonly TraceSwitch FocusTracing = new TraceSwitch("FocusTracing", "Debug focus/active control/enter/leave");
        private static readonly BooleanSwitch AssertOnControlCreateSwitch = new BooleanSwitch("AssertOnControlCreate", "Assert when anything directly deriving from control is created.");
        internal static readonly BooleanSwitch TraceMnemonicProcessing = new BooleanSwitch("TraceCanProcessMnemonic", "Trace mnemonic processing calls to assure right child-parent call ordering.");
 
        internal void TraceCanProcessMnemonic(){
            if( TraceMnemonicProcessing.Enabled ){
            string str;
                try {
                    str = string.Format( CultureInfo.CurrentCulture, "{0}<{1}>", this.GetType().Name, this.Text );
                    int maxFrameCount = new StackTrace().FrameCount;
                    if (maxFrameCount > 5) {
                        maxFrameCount = 5;
                    }
                    int frameIndex = 1;
                    while( frameIndex < maxFrameCount) {
                        StackFrame sf = new StackFrame(frameIndex);
                        if( frameIndex == 2 && sf.GetMethod().Name.Equals("CanProcessMnemonic") ){ // log immediate call if in a virtual/recursive call.
                            break;
                        }
                        str += new StackTrace(sf).ToString().TrimEnd();
                        frameIndex++;
                    }
                    if( frameIndex > 2 ){ // new CanProcessMnemonic virtual/recursive call stack.
                        str = "\r\n" + str;
                    }
                }
                catch (Exception ex) {
                    str = ex.ToString();
                }
                Debug.WriteLine( str );
            }
        }
#else
        internal static readonly TraceSwitch ControlKeyboardRouting;
        internal static readonly TraceSwitch PaletteTracing;
        internal static readonly TraceSwitch FocusTracing;
#endif
 
#if DEBUG
        internal static readonly BooleanSwitch BufferPinkRect = new BooleanSwitch("BufferPinkRect", "Renders a pink rectangle with painting double buffered controls");
        internal static readonly BooleanSwitch BufferDisabled = new BooleanSwitch("BufferDisabled", "Makes double buffered controls non-double buffered");
#else
        internal static readonly BooleanSwitch BufferPinkRect;
#endif
 
        private static int WM_GETCONTROLNAME;
        private static int WM_GETCONTROLTYPE;
 
        static Control() {
            WM_GETCONTROLNAME = SafeNativeMethods.RegisterWindowMessage("WM_GETCONTROLNAME");
            WM_GETCONTROLTYPE = SafeNativeMethods.RegisterWindowMessage("WM_GETCONTROLTYPE");
 
        }
 
        internal const int STATE_CREATED                = 0x00000001;
        internal const int STATE_VISIBLE                = 0x00000002;
        internal const int STATE_ENABLED                = 0x00000004;
        internal const int STATE_TABSTOP                = 0x00000008;
        internal const int STATE_RECREATE               = 0x00000010;
        internal const int STATE_MODAL                  = 0x00000020;
        internal const int STATE_ALLOWDROP              = 0x00000040;
        internal const int STATE_DROPTARGET             = 0x00000080;
        internal const int STATE_NOZORDER               = 0x00000100;
        internal const int STATE_LAYOUTDEFERRED         = 0x00000200;
        internal const int STATE_USEWAITCURSOR          = 0x00000400;
        internal const int STATE_DISPOSED               = 0x00000800;
        internal const int STATE_DISPOSING              = 0x00001000;
        internal const int STATE_MOUSEENTERPENDING      = 0x00002000;
        internal const int STATE_TRACKINGMOUSEEVENT     = 0x00004000;
        internal const int STATE_THREADMARSHALLPENDING  = 0x00008000;
        internal const int STATE_SIZELOCKEDBYOS         = 0x00010000;
        internal const int STATE_CAUSESVALIDATION       = 0x00020000;
        internal const int STATE_CREATINGHANDLE         = 0x00040000;
        internal const int STATE_TOPLEVEL               = 0x00080000;
        internal const int STATE_ISACCESSIBLE           = 0x00100000;
        internal const int STATE_OWNCTLBRUSH            = 0x00200000;
        internal const int STATE_EXCEPTIONWHILEPAINTING = 0x00400000;
        internal const int STATE_LAYOUTISDIRTY          = 0x00800000;
        internal const int STATE_CHECKEDHOST            = 0x01000000;
        internal const int STATE_HOSTEDINDIALOG         = 0x02000000;
        internal const int STATE_DOUBLECLICKFIRED       = 0x04000000;
        internal const int STATE_MOUSEPRESSED           = 0x08000000;
        internal const int STATE_VALIDATIONCANCELLED    = 0x10000000;
        internal const int STATE_PARENTRECREATING       = 0x20000000;
        internal const int STATE_MIRRORED               = 0x40000000;        
 
        // HACK HACK HACK - when we change RightToLeft, we need to change the scrollbar thumb.
        // We can't do that until after the control has been created, and all the items added
        // back. This is because the system control won't know the nMin and nMax of the scroll
        // bar until the items are added. So in RightToLeftChanged, we set a flag that indicates
        // that we want to set the scroll position. In OnHandleCreated we check this flag,
        // and if set, we BeginInvoke. We have to BeginInvoke since we have to wait until the items
        // are added. We only want to do this when RightToLeft changes thus the flags 
        // STATE2_HAVEINVOKED and STATE2_SETSCROLLPOS. Otherwise we would do this on each HandleCreated.
        private  const int STATE2_HAVEINVOKED                       = 0x00000001;
        private  const int STATE2_SETSCROLLPOS                      = 0x00000002;
        private  const int STATE2_LISTENINGTOUSERPREFERENCECHANGED  = 0x00000004;   // set when the control is listening to SystemEvents.UserPreferenceChanged.
        internal const int STATE2_INTERESTEDINUSERPREFERENCECHANGED = 0x00000008;   // if set, the control will listen to SystemEvents.UserPreferenceChanged when TopLevel is true and handle is created.
        internal const int STATE2_MAINTAINSOWNCAPTUREMODE           = 0x00000010;   // if set, the control DOES NOT necessarily take capture on MouseDown
        private  const int STATE2_BECOMINGACTIVECONTROL             = 0x00000020;   // set to true by ContainerControl when this control is becoming its active control
 
        private  const int STATE2_CLEARLAYOUTARGS                   = 0x00000040;   // if set, the next time PerformLayout is called, cachedLayoutEventArg will be cleared.
        private  const int STATE2_INPUTKEY                          = 0x00000080;
        private  const int STATE2_INPUTCHAR                         = 0x00000100;
        private  const int STATE2_UICUES                            = 0x00000200;
        private  const int STATE2_ISACTIVEX                         = 0x00000400;
        internal const int STATE2_USEPREFERREDSIZECACHE             = 0x00000800;
        internal const int STATE2_TOPMDIWINDOWCLOSING               = 0x00001000;
        internal const int STATE2_CURRENTLYBEINGSCALED              = 0x00002000;   // if set, the control is being scaled, currently
 
        private static readonly object EventAutoSizeChanged           = new object();
        private static readonly object EventKeyDown                   = new object();
        private static readonly object EventKeyPress                  = new object();
        private static readonly object EventKeyUp                     = new object();
        private static readonly object EventMouseDown                 = new object();
        private static readonly object EventMouseEnter                = new object();
        private static readonly object EventMouseLeave                = new object();
        private static readonly object EventDpiChangedBeforeParent    = new object();
        private static readonly object EventDpiChangedAfterParent     = new object();
        private static readonly object EventMouseHover                = new object();
        private static readonly object EventMouseMove                 = new object();
        private static readonly object EventMouseUp                   = new object();
        private static readonly object EventMouseWheel                = new object();
        private static readonly object EventClick                     = new object();
        private static readonly object EventClientSize                = new object();
        private static readonly object EventDoubleClick               = new object();
        private static readonly object EventMouseClick                = new object();
        private static readonly object EventMouseDoubleClick          = new object();
        private static readonly object EventMouseCaptureChanged       = new object();
        private static readonly object EventMove                      = new object();
        private static readonly object EventResize                    = new object();
        private static readonly object EventLayout                    = new object();
        private static readonly object EventGotFocus                  = new object();
        private static readonly object EventLostFocus                 = new object();
        private static readonly object EventEnabledChanged            = new object();
        private static readonly object EventEnter                     = new object();
        private static readonly object EventLeave                     = new object();
        private static readonly object EventHandleCreated             = new object();
        private static readonly object EventHandleDestroyed           = new object();
        private static readonly object EventVisibleChanged            = new object();
        private static readonly object EventControlAdded              = new object();
        private static readonly object EventControlRemoved            = new object();
        private static readonly object EventChangeUICues              = new object();
        private static readonly object EventSystemColorsChanged       = new object();
        private static readonly object EventValidating                = new object();
        private static readonly object EventValidated                 = new object();
        private static readonly object EventStyleChanged              = new object();
        private static readonly object EventImeModeChanged            = new object();
        private static readonly object EventHelpRequested             = new object();
        private static readonly object EventPaint                     = new object();
        private static readonly object EventInvalidated               = new object();
        private static readonly object EventQueryContinueDrag         = new object();
        private static readonly object EventGiveFeedback              = new object();
        private static readonly object EventDragEnter                 = new object();
        private static readonly object EventDragLeave                 = new object();
        private static readonly object EventDragOver                  = new object();
        private static readonly object EventDragDrop                  = new object();
        private static readonly object EventQueryAccessibilityHelp    = new object();
        private static readonly object EventBackgroundImage           = new object();
        private static readonly object EventBackgroundImageLayout     = new object();
        private static readonly object EventBindingContext            = new object();
        private static readonly object EventBackColor                 = new object();
        private static readonly object EventParent                    = new object();
        private static readonly object EventVisible                   = new object();
        private static readonly object EventText                      = new object();
        private static readonly object EventTabStop                   = new object();
        private static readonly object EventTabIndex                  = new object();
        private static readonly object EventSize                      = new object();
        private static readonly object EventRightToLeft               = new object();
        private static readonly object EventLocation                  = new object();
        private static readonly object EventForeColor                 = new object();
        private static readonly object EventFont                      = new object();
        private static readonly object EventEnabled                   = new object();
        private static readonly object EventDock                      = new object();
        private static readonly object EventCursor                    = new object();
        private static readonly object EventContextMenu               = new object();
        private static readonly object EventContextMenuStrip          = new object();
        private static readonly object EventCausesValidation          = new object();
        private static readonly object EventRegionChanged             = new object();
        private static readonly object EventMarginChanged             = new object();
        internal static readonly object EventPaddingChanged           = new object();
        private static readonly object EventPreviewKeyDown            = new object();
 
        #if WIN95_SUPPORT
        private static int mouseWheelMessage = NativeMethods.WM_MOUSEWHEEL;
        private static bool mouseWheelRoutingNeeded;
        private static bool mouseWheelInit;
        #endif
 
        private static int threadCallbackMessage;
 
        // Initially check for illegal multithreading based on whether the
        // debugger is attached.
        [ResourceExposure(ResourceScope.Process)]
        private static bool checkForIllegalCrossThreadCalls = Debugger.IsAttached;
        private static ContextCallback invokeMarshaledCallbackHelperDelegate;
 
        [ ThreadStatic ]
        private static bool inCrossThreadSafeCall = false;
 
// disable csharp compiler warning #0414: field assigned unused value
#pragma warning disable 0414
        [ ThreadStatic ]
        internal static HelpInfo currentHelpInfo = null;
#pragma warning restore 0414
 
        private static FontHandleWrapper defaultFontHandleWrapper;
 
        private const short PaintLayerBackground = 1;
        private const short PaintLayerForeground = 2;
 
        private const byte RequiredScalingEnabledMask = 0x10;
        private const byte RequiredScalingMask = 0x0F;
 
        private const byte HighOrderBitMask = 0x80;
 
        private static Font defaultFont;
 
        // Property store keys for properties.  The property store allocates most efficiently
        // in groups of four, so we try to lump properties in groups of four based on how
        // likely they are going to be used in a group.
        //
        private static readonly int PropName                                = PropertyStore.CreateKey();
        private static readonly int PropBackBrush                           = PropertyStore.CreateKey();
        private static readonly int PropFontHeight                          = PropertyStore.CreateKey();
        private static readonly int PropCurrentAmbientFont                  = PropertyStore.CreateKey();
 
        private static readonly int PropControlsCollection                  = PropertyStore.CreateKey();
        private static readonly int PropBackColor                           = PropertyStore.CreateKey();
        private static readonly int PropForeColor                           = PropertyStore.CreateKey();
        private static readonly int PropFont                                = PropertyStore.CreateKey();
 
        private static readonly int PropBackgroundImage                     = PropertyStore.CreateKey();
        private static readonly int PropFontHandleWrapper                   = PropertyStore.CreateKey();
        private static readonly int PropUserData                            = PropertyStore.CreateKey();
        private static readonly int PropContextMenu                         = PropertyStore.CreateKey();
 
        private static readonly int PropCursor                              = PropertyStore.CreateKey();
        private static readonly int PropRegion                              = PropertyStore.CreateKey();
        private static readonly int PropRightToLeft                         = PropertyStore.CreateKey();
 
        private static readonly int PropBindings                            = PropertyStore.CreateKey();
        private static readonly int PropBindingManager                      = PropertyStore.CreateKey();
        private static readonly int PropAccessibleDefaultActionDescription  = PropertyStore.CreateKey();
        private static readonly int PropAccessibleDescription               = PropertyStore.CreateKey();
 
        private static readonly int PropAccessibility                       = PropertyStore.CreateKey();
        private static readonly int PropNcAccessibility                     = PropertyStore.CreateKey();
        private static readonly int PropAccessibleName                      = PropertyStore.CreateKey();
        private static readonly int PropAccessibleRole                      = PropertyStore.CreateKey();
 
        private static readonly int PropPaintingException                   = PropertyStore.CreateKey();
        private static readonly int PropActiveXImpl                         = PropertyStore.CreateKey();
        private static readonly int PropControlVersionInfo                  = PropertyStore.CreateKey();
        private static readonly int PropBackgroundImageLayout               = PropertyStore.CreateKey();
 
        private static readonly int PropAccessibleHelpProvider              = PropertyStore.CreateKey();
        private static readonly int PropContextMenuStrip                    = PropertyStore.CreateKey();
        private static readonly int PropAutoScrollOffset                    = PropertyStore.CreateKey();
        private static readonly int PropUseCompatibleTextRendering          = PropertyStore.CreateKey();
 
        private static readonly int PropImeWmCharsToIgnore                  = PropertyStore.CreateKey();
        private static readonly int PropImeMode                             = PropertyStore.CreateKey();
        private static readonly int PropDisableImeModeChangedCount          = PropertyStore.CreateKey();
        private static readonly int PropLastCanEnableIme                    = PropertyStore.CreateKey();
 
        private static readonly int PropCacheTextCount                      = PropertyStore.CreateKey();
        private static readonly int PropCacheTextField                      = PropertyStore.CreateKey();
        private static readonly int PropAmbientPropertiesService            = PropertyStore.CreateKey();
 
        private static bool needToLoadComCtl = true;
 
        // This switch determines the default text rendering engine to use by some controls that support switching rendering engine.
        // CheckedListBox, PropertyGrid, GroupBox, Label and LinkLabel, and ButtonBase controls.
        // True means use GDI+, false means use GDI (TextRenderer).
        internal static bool UseCompatibleTextRenderingDefault = true;
 
        ///////////////////////////////////////////////////////////////////////
        // Control per instance members
        //
        // Note: Do not add anything to this list unless absolutely neccessary.
        //       Every control on a form has the overhead of all of these
        //       variables!
        //
        // Begin Members {
 
        // List of properties that are generally set, so we keep them directly on
        // control.
        //
 
        // Resist the temptation to make this variable 'internal' rather than
        // private. Handle access should be tightly controlled, and is in this
        // file.  Making it 'internal' makes controlling it quite difficult.
        private ControlNativeWindow           window;
 
        private Control                       parent;
        private Control                       reflectParent;
        private CreateParams                  createParams;
        private int                           x;                      // CONSIDER: changing this to short
        private int                           y;
        private int                           width;
        private int                           height;
        private int                           clientWidth;
        private int                           clientHeight;
        private int                           state;                  // See STATE_ constants above
        private int                           state2;                 // See STATE2_ constants above
        private ControlStyles                 controlStyle;           // User supplied control style
        private int                           tabIndex;
        private string                        text;                   // See ControlStyles.CacheText for usage notes
        private byte                          layoutSuspendCount;
        private byte                          requiredScaling;        // bits 0-4: BoundsSpecified stored in RequiredScaling property.  Bit 5: RequiredScalingEnabled property.
        private PropertyStore                 propertyStore;          // Contains all properties that are not always set.
        private NativeMethods.TRACKMOUSEEVENT trackMouseEvent;
        private short                         updateCount;
        private LayoutEventArgs               cachedLayoutEventArgs;
        private Queue                         threadCallbackList;
        internal int                          deviceDpi;
 
 
        // for keeping track of our ui state for focus and keyboard cues.  using a member variable
        // here because we hit this a lot
        //
        private int uiCuesState;
 
        private const int UISTATE_FOCUS_CUES_MASK               = 0x000F;                 
        private const int UISTATE_FOCUS_CUES_HIDDEN             = 0x0001;
        private const int UISTATE_FOCUS_CUES_SHOW               = 0x0002;
        private const int UISTATE_KEYBOARD_CUES_MASK            = 0x00F0;
        private const int UISTATE_KEYBOARD_CUES_HIDDEN          = 0x0010;
        private const int UISTATE_KEYBOARD_CUES_SHOW            = 0x0020;
 
        [ThreadStatic]
        private static byte[] tempKeyboardStateArray;
 
        // } End Members
        ///////////////////////////////////////////////////////////////////////
 
#if DEBUG
        internal int LayoutSuspendCount {
            get { return layoutSuspendCount; }
        }
 
        internal void AssertLayoutSuspendCount(int value) {
            Debug.Assert(value == layoutSuspendCount, "Suspend/Resume layout mismatch!");
        }
 
/*
example usage
 
#if DEBUG
        int dbgLayoutCheck = LayoutSuspendCount;
#endif
#if DEBUG
        AssertLayoutSuspendCount(dbgLayoutCheck);
#endif
*/
 
#endif
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Control"]/*' />
        /// <devdoc>
        /// <para>Initializes a new instance of the <see cref='System.Windows.Forms.Control'/> class.</para>
        /// </devdoc>
        public Control() : this(true) {
        }
 
        /// <devdoc>
        /// </devdoc>
        internal Control(bool autoInstallSyncContext) : base() {
#if DEBUG
            if (AssertOnControlCreateSwitch.Enabled) {
                Debug.Assert(this.GetType().BaseType != typeof(Control), "Direct derivative of Control Created: " + this.GetType().FullName);
                Debug.Assert(this.GetType() != typeof(Control), "Control Created!");
            }
#endif
            propertyStore = new PropertyStore();
 
            DpiHelper.InitializeDpiHelperForWinforms();
            // Initialize DPI to the value on the primary screen, we will have the correct value when the Handle is created.
            deviceDpi = DpiHelper.DeviceDpi;
 
            window = new ControlNativeWindow(this);
            RequiredScalingEnabled = true;
            RequiredScaling = BoundsSpecified.All;
            tabIndex = -1;
 
            state = STATE_VISIBLE | STATE_ENABLED | STATE_TABSTOP | STATE_CAUSESVALIDATION;
            state2 = STATE2_INTERESTEDINUSERPREFERENCECHANGED;
            SetStyle(ControlStyles.AllPaintingInWmPaint |
                     ControlStyles.UserPaint |
                     ControlStyles.StandardClick |
                     ControlStyles.StandardDoubleClick |
                     ControlStyles.UseTextForAccessibility |
                     ControlStyles.Selectable,true);
 
#if WIN95_SUPPORT
            InitMouseWheelSupport();
#endif
 
            // We baked the "default default" margin and min size into CommonProperties
            // so that in the common case the PropertyStore would be empty.  If, however,
            // someone overrides these Default* methads, we need to write the default
            // value into the PropertyStore in the ctor.
            //
            if(DefaultMargin != CommonProperties.DefaultMargin) {
                Margin = DefaultMargin;
            }
            if(DefaultMinimumSize != CommonProperties.DefaultMinimumSize) {
                MinimumSize = DefaultMinimumSize;
            }
            if(DefaultMaximumSize != CommonProperties.DefaultMaximumSize) {
                MaximumSize = DefaultMaximumSize;
            }
 
            // Compute our default size.
            //
            Size defaultSize = DefaultSize;
            width = defaultSize.Width;
            height = defaultSize.Height;
 
            // DefaultSize may have hit GetPreferredSize causing a PreferredSize to be cached.  The
            // PreferredSize may change as a result of the current size.  Since a  SetBoundsCore did
            // not happen, so we need to clear the preferredSize cache manually.
            CommonProperties.xClearPreferredSizeCache(this);
 
            if (width != 0 && height != 0) {
                NativeMethods.RECT rect = new NativeMethods.RECT();
                rect.left = rect.right = rect.top = rect.bottom = 0;
 
                CreateParams cp = CreateParams;
 
                AdjustWindowRectEx(ref rect, cp.Style, false, cp.ExStyle);
                clientWidth = width - (rect.right - rect.left);
                clientHeight = height - (rect.bottom - rect.top);
            }
 
 
            // Set up for async operations on this thread.
            if (autoInstallSyncContext) {
                WindowsFormsSynchronizationContext.InstallIfNeeded();
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Control1"]/*' />
        /// <devdoc>
        /// <para>Initializes a new instance of the <see cref='System.Windows.Forms.Control'/> class.</para>
        /// </devdoc>
        public Control( string text ) : this( (Control) null, text ) {
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Control2"]/*' />
        /// <devdoc>
        /// <para>Initializes a new instance of the <see cref='System.Windows.Forms.Control'/> class.</para>
        /// </devdoc>
        public Control( string text, int left, int top, int width, int height ) :
                    this( (Control) null, text, left, top, width, height ) {
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Control3"]/*' />
        /// <devdoc>
        /// <para>Initializes a new instance of the <see cref='System.Windows.Forms.Control'/> class.</para>
        /// </devdoc>
        public Control( Control parent, string text ) : this() {
            this.Parent = parent;
            this.Text = text;
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Control4"]/*' />
        /// <devdoc>
        /// <para>Initializes a new instance of the <see cref='System.Windows.Forms.Control'/> class.</para>
        /// </devdoc>
        public Control( Control parent, string text, int left, int top, int width, int height ) : this( parent, text ) {
            this.Location = new Point( left, top );
            this.Size = new Size( width, height );
        }
 
        /// <summary>
        /// gets or sets control Dpi awareness context value.
        /// </summary>
        internal DpiAwarenessContext DpiAwarenessContext {
            get {
                return window.DpiAwarenessContext;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.AccessibilityObject"]/*' />
        /// <devdoc>
        ///      The Accessibility Object for this Control
        /// </devdoc>
        [
        Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlAccessibilityObjectDescr)
        ]
        public AccessibleObject AccessibilityObject {
            get {
                AccessibleObject accessibleObject = (AccessibleObject)Properties.GetObject(PropAccessibility);
                if (accessibleObject == null) {
                    accessibleObject = CreateAccessibilityInstance();
                    // this is a security check. we want to enforce that we only return
                    // ControlAccessibleObject and not some other derived class
                    if(!(accessibleObject is ControlAccessibleObject)) {
                        Debug.Fail("Accessible objects for controls must be derived from ControlAccessibleObject.");
                        return null;
                    }
                    Properties.SetObject(PropAccessibility, accessibleObject);
                }
 
                Debug.Assert(accessibleObject != null, "Failed to create accessibility object");
                return accessibleObject;
            }
        }
 
        /// <devdoc>
        ///      Private accessibility object for control, used to wrap the object that
        ///      OLEACC.DLL creates to represent the control's non-client (NC) region.
        /// </devdoc>
        private AccessibleObject NcAccessibilityObject {
            get {
                AccessibleObject ncAccessibleObject = (AccessibleObject)Properties.GetObject(PropNcAccessibility);
                if (ncAccessibleObject == null) {
                    ncAccessibleObject = new ControlAccessibleObject(this, NativeMethods.OBJID_WINDOW);
                    Properties.SetObject(PropNcAccessibility, ncAccessibleObject);
                }
 
                Debug.Assert(ncAccessibleObject != null, "Failed to create NON-CLIENT accessibility object");
                return ncAccessibleObject;
            }
        }
 
        /// <devdoc>
        ///     Returns a specific AccessibleObject associated with this
        ///     control, based on standard "accessibile object id".
        /// </devdoc>
        /// <internalonly/>
        private AccessibleObject GetAccessibilityObject(int accObjId) {
            AccessibleObject accessibleObject;
 
            switch (accObjId) {
                case NativeMethods.OBJID_CLIENT:
                    accessibleObject = this.AccessibilityObject;
                    break;
                case NativeMethods.OBJID_WINDOW:
                    accessibleObject = this.NcAccessibilityObject;
                    break;
                default:
                    if (accObjId > 0) {
                        accessibleObject = this.GetAccessibilityObjectById(accObjId);
                    } else {
                        accessibleObject = null;
                    }
                    break;
            }
 
            return accessibleObject;
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.GetAccessibilityObjectById"]/*' />
        /// <devdoc>
        ///      Returns a specific AccessibleObbject associated w/ the objectID
        /// </devdoc>
        protected virtual AccessibleObject GetAccessibilityObjectById(int objectId) {
            if (AccessibilityImprovements.Level3 && this is IAutomationLiveRegion) {
                return this.AccessibilityObject;
            }
 
            return null;
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.AccessibleDefaultActionDescription"]/*' />
        /// <devdoc>
        ///      The default action description of the control
        /// </devdoc>
        [
        SRCategory(SR.CatAccessibility),
        Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlAccessibleDefaultActionDescr)
        ]
        public string AccessibleDefaultActionDescription {
            get {
                return (string)Properties.GetObject(PropAccessibleDefaultActionDescription);
            }
            set {
                Properties.SetObject(PropAccessibleDefaultActionDescription, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.AccessibleDescription"]/*' />
        /// <devdoc>
        ///      The accessible description of the control
        /// </devdoc>
        [
        SRCategory(SR.CatAccessibility),
        DefaultValue(null),
        Localizable(true),
        SRDescription(SR.ControlAccessibleDescriptionDescr)
        ]
        public string AccessibleDescription {
            get {
                return (string)Properties.GetObject(PropAccessibleDescription);
            }
            set {
                Properties.SetObject(PropAccessibleDescription, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.AccessibleName"]/*' />
        /// <devdoc>
        ///      The accessible name of the control
        /// </devdoc>
        [
        SRCategory(SR.CatAccessibility),
        DefaultValue(null),
        Localizable(true),
        SRDescription(SR.ControlAccessibleNameDescr)
        ]
        public string AccessibleName {
            get {
                return (string)Properties.GetObject(PropAccessibleName);
            }
 
            set {
                Properties.SetObject(PropAccessibleName, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.AccessibleRole"]/*' />
        /// <devdoc>
        ///      The accessible role of the control
        /// </devdoc>
        [
        SRCategory(SR.CatAccessibility),
        DefaultValue(AccessibleRole.Default),
        SRDescription(SR.ControlAccessibleRoleDescr)
        ]
        public AccessibleRole AccessibleRole {
 
            get {
                bool found;
                int role = Properties.GetInteger(PropAccessibleRole, out found);
                if (found) {
                    return (AccessibleRole)role;
                }
                else {
                    return AccessibleRole.Default;
                }
            }
 
            set {
                //valid values are -1 to 0x40
                if (!ClientUtils.IsEnumValid(value, (int)value, (int)AccessibleRole.Default, (int)AccessibleRole.OutlineButton)) {
                    throw new InvalidEnumArgumentException("value", (int)value, typeof(AccessibleRole));
                }
                Properties.SetInteger(PropAccessibleRole, (int)value);
            }
        }
 
        /// <devdoc>
        ///     Helper method for retrieving an ActiveX property.  We abstract these
        ///     to another method so we do not force JIT the ActiveX codebase.
        /// </devdoc>
        private Color ActiveXAmbientBackColor {
            get {
                return ActiveXInstance.AmbientBackColor;
            }
        }
 
        /// <devdoc>
        ///     Helper method for retrieving an ActiveX property.  We abstract these
        ///     to another method so we do not force JIT the ActiveX codebase.
        /// </devdoc>
        private Color ActiveXAmbientForeColor {
            get {
                return ActiveXInstance.AmbientForeColor;
            }
        }
 
        /// <devdoc>
        ///     Helper method for retrieving an ActiveX property.  We abstract these
        ///     to another method so we do not force JIT the ActiveX codebase.
        /// </devdoc>
        private Font ActiveXAmbientFont {
            [ResourceExposure(ResourceScope.Process)]
            [ResourceConsumption(ResourceScope.Process)]
            get {
                return ActiveXInstance.AmbientFont;
            }
        }
 
        /// <devdoc>
        ///     Helper method for retrieving an ActiveX property.  We abstract these
        ///     to another method so we do not force JIT the ActiveX codebase.
        /// </devdoc>
        private bool ActiveXEventsFrozen {
            get {
                return ActiveXInstance.EventsFrozen;
            }
        }
 
        /// <devdoc>
        ///     Helper method for retrieving an ActiveX property.  We abstract these
        ///     to another method so we do not force JIT the ActiveX codebase.
        /// </devdoc>
        private IntPtr ActiveXHWNDParent {
            get {
                return ActiveXInstance.HWNDParent;
            }
        }
 
        /// <devdoc>
        ///      Retrieves the ActiveX control implementation for
        ///      this control.  This will demand create the implementation
        ///      if it does not already exist.
        /// </devdoc>
        private ActiveXImpl ActiveXInstance {
            get {
                ActiveXImpl activeXImpl = (ActiveXImpl)Properties.GetObject(PropActiveXImpl);
                if (activeXImpl == null) {
 
                    // Don't allow top level objects to be hosted
                    // as activeX controls.
                    //
                    if (GetState(STATE_TOPLEVEL)) {
                        throw new NotSupportedException(SR.GetString(SR.AXTopLevelSource));
                    }
 
                    activeXImpl = new ActiveXImpl(this);
                    
                    // PERF: IsActiveX is called quite a bit - checked everywhere from sizing to event raising.  Using a state
                    // bit to track PropActiveXImpl instead of fetching from the property store.
                    SetState2(STATE2_ISACTIVEX, true);
                    Properties.SetObject(PropActiveXImpl, activeXImpl);
                }
 
                return activeXImpl;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.AllowDrop"]/*' />
        /// <devdoc>
        ///     The AllowDrop property. If AllowDrop is set to true then
        ///     this control will allow drag and drop operations and events to be used.
        /// </devdoc>
        [
        SRCategory(SR.CatBehavior),
        DefaultValue(false),
        SRDescription(SR.ControlAllowDropDescr)
        ]
        public virtual bool AllowDrop {
            get {
                return GetState(STATE_ALLOWDROP);
            }
 
            set {
                if (GetState(STATE_ALLOWDROP) != value) {
                    // Since we won't call SetAcceptDrops without a handle,
                    // we do the security demand here. Without this demand
                    // we are still safe, but you get the exception at an
                    // odd time. This gives a better experience.
                    //
                    if (value && !IsHandleCreated) {
                        IntSecurity.ClipboardRead.Demand();
                    }
 
                    SetState(STATE_ALLOWDROP, value);
 
                    if (IsHandleCreated) {
                        try {
                            SetAcceptDrops(value);
                        }
                        catch {
                            // If there is an error, back out the AllowDrop state...
                            //
                            SetState(STATE_ALLOWDROP, !value);
                            throw;
                        }
                    }
                }
            }
        }
 
        // Queries the Site for AmbientProperties.  May return null.
        // Do not confuse with inheritedProperties -- the service is turned to
        // after we've exhausted inheritedProperties.
        private AmbientProperties AmbientPropertiesService {
            get {
                bool contains;
                AmbientProperties props = (AmbientProperties)Properties.GetObject(PropAmbientPropertiesService, out contains);
                if (!contains) {
                    if (Site != null) {
                        props = (AmbientProperties)Site.GetService(typeof(AmbientProperties));
                    }
                    else {
                        props = (AmbientProperties)GetService(typeof(AmbientProperties));
                    }
 
                    if (props != null) {
                        Properties.SetObject(PropAmbientPropertiesService, props);
                    }
                }
                return props;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Anchor"]/*' />
        /// <devdoc>
        ///     The current value of the anchor property. The anchor property
        ///     determines which edges of the control are anchored to the container's
        ///     edges.
        /// </devdoc>
        [
        SRCategory(SR.CatLayout),
        Localizable(true),
        DefaultValue(CommonProperties.DefaultAnchor),
        SRDescription(SR.ControlAnchorDescr),
        RefreshProperties(RefreshProperties.Repaint)
        ]
        public virtual AnchorStyles Anchor {
            get {
                return DefaultLayout.GetAnchor(this);
            }
            set {
                DefaultLayout.SetAnchor(ParentInternal, this, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.AutoSize"]/*' />
        [SRCategory(SR.CatLayout)]
        [RefreshProperties(RefreshProperties.All)]
        [Localizable(true)]
        [DefaultValue(CommonProperties.DefaultAutoSize)]
        [SRDescription(SR.ControlAutoSizeDescr)]
        [Browsable(false), EditorBrowsable(EditorBrowsableState.Never),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public virtual bool AutoSize {
            get { return CommonProperties.GetAutoSize(this); }
            set {
                if(value != AutoSize) {
                    CommonProperties.SetAutoSize(this, value);
                    if(ParentInternal != null) {
                        // DefaultLayout does not keep anchor information until it needs to.  When
                        // AutoSize became a common property, we could no longer blindly call into
                        // DefaultLayout, so now we do a special InitLayout just for DefaultLayout.
                        if(value && ParentInternal.LayoutEngine == DefaultLayout.Instance) {
                            ParentInternal.LayoutEngine.InitLayout(this, BoundsSpecified.Size);
                        }
                        LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.AutoSize);
                    }
 
                    OnAutoSizeChanged(EventArgs.Empty);
                }
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.AutoSizeChanged"]/*' />
        [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ControlOnAutoSizeChangedDescr)]
        [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
        public event EventHandler AutoSizeChanged {
            add {
                Events.AddHandler(EventAutoSizeChanged, value);
            }
            remove {
                Events.RemoveHandler(EventAutoSizeChanged, value);
            }
        }
 
        /// <devdoc>
        /// Controls the location of where this control is scrolled to in ScrollableControl.ScrollControlIntoView.
        /// Default is the upper left hand corner of the control.
        /// </devdoc>
        [
        Browsable(false),
        EditorBrowsable(EditorBrowsableState.Advanced),
        DefaultValue(typeof(Point), "0, 0")
        ]
        public virtual Point AutoScrollOffset {
            get {
                if (Properties.ContainsObject(PropAutoScrollOffset)) {
                    return (Point)Properties.GetObject(PropAutoScrollOffset);
                }
                return Point.Empty;
            }
            set {
                if (AutoScrollOffset != value) {
                    Properties.SetObject(PropAutoScrollOffset, value);
                }
            }
        }
 
        protected void SetAutoSizeMode(AutoSizeMode mode) {
            CommonProperties.SetAutoSizeMode(this, mode);
        }
 
        protected AutoSizeMode GetAutoSizeMode() {
            return CommonProperties.GetAutoSizeMode(this);
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.LayoutEngine"]/*' />
        // Public because this is interesting for ControlDesigners.
        [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)]
        public virtual LayoutEngine LayoutEngine {
            get { return DefaultLayout.Instance; }
        }
 
        /// <devdoc>
        ///     The GDI brush for our background color.
        ///     Whidbey Note: Made this internal, since we need to use this in ButtonStandardAdapter. Also, renamed
        ///                   from BackBrush to BackColorBrush due to a naming conflict with DataGrid's BackBrush.
        /// </devdoc>
        internal IntPtr BackColorBrush {
            [ResourceExposure(ResourceScope.Process)]
            [ResourceConsumption(ResourceScope.Process)]
            get {
                object customBackBrush = Properties.GetObject(PropBackBrush);
                if (customBackBrush != null) {
 
                    // We already have a valid brush.  Unbox, and return.
                    //
                    return (IntPtr)customBackBrush;
                }
 
                if (!Properties.ContainsObject(PropBackColor)) {
 
                    // No custom back color.  See if we can get to our parent.
                    // The color check here is to account for parents and children who
                    // override the BackColor property.
                    //
                    if (parent != null && parent.BackColor == BackColor) {
                        return parent.BackColorBrush;
                    }
                }
 
                // No parent, or we have a custom back color.  Either way, we need to
                // create our own.
                //
                Color color = BackColor;
                IntPtr backBrush;
 
                if (ColorTranslator.ToOle(color) < 0) {
                    backBrush = SafeNativeMethods.GetSysColorBrush(ColorTranslator.ToOle(color) & 0xFF);
                    SetState(STATE_OWNCTLBRUSH, false);
                }
                else {
                    backBrush = SafeNativeMethods.CreateSolidBrush(ColorTranslator.ToWin32(color));
                    SetState(STATE_OWNCTLBRUSH, true);
                }
 
                Debug.Assert(backBrush != IntPtr.Zero, "Failed to create brushHandle");
                Properties.SetObject(PropBackBrush, backBrush);
 
                return backBrush;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.BackColor"]/*' />
        /// <devdoc>
        ///     The background color of this control. This is an ambient property and
        ///     will always return a non-null value.
        /// </devdoc>
        [
        SRCategory(SR.CatAppearance),
        DispId(NativeMethods.ActiveX.DISPID_BACKCOLOR),
        SRDescription(SR.ControlBackColorDescr)
        ]
        public virtual Color BackColor {
            get {
                Color c = RawBackColor; // inheritedProperties.BackColor
                if (!c.IsEmpty) {
                    return c;
                }
 
                Control p = ParentInternal;
                if (p != null && p.CanAccessProperties) {
                    c = p.BackColor;
                    if (IsValidBackColor(c))
                    {
                        return c;
                    }
 
                }
 
                if (IsActiveX) {
                    c = ActiveXAmbientBackColor;
                }
 
                if (c.IsEmpty) {
                    AmbientProperties ambient = AmbientPropertiesService;
                    if (ambient != null)
                        c = ambient.BackColor;
                }
 
                if (!c.IsEmpty && IsValidBackColor(c))
                    return c;
                else
                    return DefaultBackColor;
            }
 
            set {
                if (!value.Equals(Color.Empty) && !GetStyle(ControlStyles.SupportsTransparentBackColor) && value.A < 255)
                    throw new ArgumentException(SR.GetString(SR.TransparentBackColorNotAllowed));
 
                Color c = BackColor;
                if (!value.IsEmpty || Properties.ContainsObject(PropBackColor)) {
                    Properties.SetColor(PropBackColor, value);
                }
 
                if (!c.Equals(BackColor)) {
                    OnBackColorChanged(EventArgs.Empty);
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.BackColorChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ControlOnBackColorChangedDescr)]
        public event EventHandler BackColorChanged {
            add {
                Events.AddHandler(EventBackColor, value);
            }
            remove {
                Events.RemoveHandler(EventBackColor, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.BackgroundImage"]/*' />
        /// <devdoc>
        ///     The background image of the control.
        /// </devdoc>
        [
        SRCategory(SR.CatAppearance),
        DefaultValue(null),
        Localizable(true),
        SRDescription(SR.ControlBackgroundImageDescr)
        ]
        public virtual Image BackgroundImage {
            get {
                return (Image)Properties.GetObject(PropBackgroundImage);
            }
            set {
                if (BackgroundImage != value) {
                    Properties.SetObject(PropBackgroundImage, value);
                    OnBackgroundImageChanged(EventArgs.Empty);
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.BackgroundImageChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ControlOnBackgroundImageChangedDescr)]
        public event EventHandler BackgroundImageChanged {
            add {
                Events.AddHandler(EventBackgroundImage, value);
            }
            remove {
                Events.RemoveHandler(EventBackgroundImage, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.BackgroundImageLayout"]/*' />
        /// <devdoc>
        ///     The BackgroundImageLayout of the control.
        /// </devdoc>
        [
        SRCategory(SR.CatAppearance),
        DefaultValue(ImageLayout.Tile),
        Localizable(true),
        SRDescription(SR.ControlBackgroundImageLayoutDescr)
        ]
        public virtual ImageLayout BackgroundImageLayout {
            get {
                bool found = Properties.ContainsObject(PropBackgroundImageLayout);
                if (!found) {
                    return ImageLayout.Tile;
                }
                else {
                    return ((ImageLayout)Properties.GetObject(PropBackgroundImageLayout));
               }
            }
            set {
                if (BackgroundImageLayout != value) {
                    //valid values are 0x0 to 0x4
                    if (!ClientUtils.IsEnumValid(value, (int)value, (int)ImageLayout.None, (int)ImageLayout.Zoom)){
                        throw new InvalidEnumArgumentException("value", (int)value, typeof(ImageLayout));
                    }
                    // Check if the value is either center, strech or zoom;
                    if (value == ImageLayout.Center || value == ImageLayout.Zoom || value == ImageLayout.Stretch) {                    
                        SetStyle(ControlStyles.ResizeRedraw, true);
                        // Only for images that support transparency.
                        if (ControlPaint.IsImageTransparent(BackgroundImage))
                        {
                            DoubleBuffered = true;    
                        }
                    }
                    Properties.SetObject(PropBackgroundImageLayout, value);
                    OnBackgroundImageLayoutChanged(EventArgs.Empty);
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.BackgroundImageLayoutChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ControlOnBackgroundImageLayoutChangedDescr)]
        public event EventHandler BackgroundImageLayoutChanged {
            add {
                Events.AddHandler(EventBackgroundImageLayout, value);
            }
            remove {
                Events.RemoveHandler(EventBackgroundImageLayout, value);
            }
        }
 
        // Set/reset by ContainerControl.AssignActiveControlInternal
        internal bool BecomingActiveControl
        {
            get
            {
                return GetState2(STATE2_BECOMINGACTIVECONTROL);
            }
            set
            {
                if (value != this.BecomingActiveControl)
                {                    
                    Application.ThreadContext.FromCurrent().ActivatingControl = (value) ? this : null;
                    SetState2(STATE2_BECOMINGACTIVECONTROL, value);
                }
            }
        }
 
        private bool ShouldSerializeAccessibleName() {
            string accName = this.AccessibleName;
            return accName != null && accName.Length > 0;
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.ResetBindings"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Never)]
        public void ResetBindings() {
            ControlBindingsCollection bindings = (ControlBindingsCollection)Properties.GetObject(PropBindings);
            if (bindings != null) {
                bindings.Clear();
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.BindingContextInternal"]/*' />
        /// <devdoc>
        ///    BindingContextInternal provides a mechanism so that controls like SplitContainer that inherit from the
        ///    ContainerControl can bypass the "containerControls" bindingContext property and do what the other simple controls
        ///    do.
        /// </devdoc>
        internal BindingContext BindingContextInternal
        {
            get
            {
                // See if we have locally overridden the binding manager.
                //
                BindingContext context = (BindingContext) Properties.GetObject(PropBindingManager);
                if (context != null) {
                    return context;
                }
 
                // Otherwise, see if the parent has one for us.
                //
                Control p = ParentInternal;
                if (p != null && p.CanAccessProperties) {
                    return p.BindingContext;
                }
 
                // Otherwise, we have no binding manager available.
                //
                return null;
            }
            set
            {
                BindingContext oldContext = (BindingContext) Properties.GetObject(PropBindingManager);
                BindingContext newContext = value;
 
                if (oldContext != newContext) {
                    Properties.SetObject(PropBindingManager, newContext);
 
                    // the property change will wire up the bindings.
                    //
                    OnBindingContextChanged(EventArgs.Empty);
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.BindingContext"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [
        Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlBindingContextDescr)
        ]
        public virtual BindingContext BindingContext {
            get {
                return BindingContextInternal;
            }
            set {
                BindingContextInternal = value;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.BindingContextChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ControlOnBindingContextChangedDescr)]
        public event EventHandler BindingContextChanged {
            add {
                Events.AddHandler(EventBindingContext, value);
            }
            remove {
                Events.RemoveHandler(EventBindingContext, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Bottom"]/*' />
        /// <devdoc>
        ///    <para>The bottom coordinate of this control.</para>
        /// </devdoc>
        [
        Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlBottomDescr),
        SRCategory(SR.CatLayout)
        ]
        public int Bottom {
            get {
                return y + height;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Bounds"]/*' />
        /// <devdoc>
        ///     The bounds of this control. This is the window coordinates of the
        ///     control in parent client coordinates.
        /// </devdoc>
        [
        Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlBoundsDescr),
        SRCategory(SR.CatLayout)
        ]
        public Rectangle Bounds {
            get {
                return new Rectangle(x, y, width, height);
            }
 
            set {
                SetBounds(value.X, value.Y, value.Width, value.Height, BoundsSpecified.All);
            }
        }
 
        /// <devdoc>
        /// </devdoc>
        /// <internalonly/>
        internal virtual bool CanAccessProperties {
            get {
                return true;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.CanFocus"]/*' />
        /// <devdoc>
        ///    <para>Indicates whether the control can receive focus. This
        ///       property is read-only.</para>
        /// </devdoc>
        [
        Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRCategory(SR.CatFocus),
        SRDescription(SR.ControlCanFocusDescr)
        ]
        public bool CanFocus {
            get {
                if (!IsHandleCreated) {
                    return false;
                }
                bool visible = SafeNativeMethods.IsWindowVisible(new HandleRef(window, Handle));
                bool enabled = SafeNativeMethods.IsWindowEnabled(new HandleRef(window, Handle));
                return (visible && enabled);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.CanRaiseEvents"]/*' />
        /// <devdoc>
        ///     Determines if events can be fired on the control.  If this control is being
        ///     hosted as an ActiveX control, this property will return false if the ActiveX
        ///     control has its events frozen.
        /// </devdoc>
        protected override bool CanRaiseEvents {
            get {
                if (IsActiveX) {
                    return !ActiveXEventsFrozen;
                }
 
                return true;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.CanSelect"]/*' />
        /// <devdoc>
        ///    <para>
        ///       Indicates whether the control can be selected. This property
        ///       is read-only.</para>
        /// </devdoc>
        [
        Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRCategory(SR.CatFocus),
        SRDescription(SR.ControlCanSelectDescr)
        ]
        public bool CanSelect {
            // We implement this to allow only AxHost to override canSelectCore, but still
            // expose the method publicly
            //
            get {
                return CanSelectCore();
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Capture"]/*' />
        /// <devdoc>
        ///    <para> Indicates whether the control has captured the mouse.</para>
        /// </devdoc>
        [
        Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRCategory(SR.CatFocus),
        SRDescription(SR.ControlCaptureDescr)
        ]
        public bool Capture {
            get {
                return CaptureInternal;
            }
 
            set {
                if (value) {
                    Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "GetCapture Demanded");
                    IntSecurity.GetCapture.Demand();
                }
                CaptureInternal = value;
            }
        }
 
        // SECURITY WARNING: This property bypasses a security demand. Use with caution!
        internal bool CaptureInternal {
            get {
                return IsHandleCreated && UnsafeNativeMethods.GetCapture() == Handle;
            }
            set {
                if (CaptureInternal != value) {
                    if (value) {
                        UnsafeNativeMethods.SetCapture(new HandleRef(this, Handle));
                    }
                    else {
                        SafeNativeMethods.ReleaseCapture();
                    }
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.CausesValidation"]/*' />
        /// <devdoc>
        ///    <para>
        ///       Indicates whether entering the control causes validation on the controls requiring validation.</para>
        /// </devdoc>
        [
        SRCategory(SR.CatFocus),
        DefaultValue(true),
        SRDescription(SR.ControlCausesValidationDescr)
        ]
        public bool CausesValidation {
            get {
                return GetState(STATE_CAUSESVALIDATION);
            }
            set {
                if (value != this.CausesValidation) {
                    SetState(STATE_CAUSESVALIDATION, value);
                    OnCausesValidationChanged(EventArgs.Empty);
                }
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.CausesValidationChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ControlOnCausesValidationChangedDescr)]
        public event EventHandler CausesValidationChanged {
            add {
                Events.AddHandler(EventCausesValidation, value);
            }
            remove {
                Events.RemoveHandler(EventCausesValidation, value);
            }
        }
 
 
        /// This is for perf. Turn this property on to temporarily enable text caching.  This is good for
        /// operations such as layout or painting where we don't expect the text to change (we will update the
        /// cache if it does) but prevents us from sending a ton of messages turing layout.  See the PaintWithErrorHandling
        /// function.
        ///
        internal bool CacheTextInternal {
            get {
 
                // check if we're caching text.
                //
                bool found;
                int cacheTextCounter = Properties.GetInteger(PropCacheTextCount, out found);
 
                return cacheTextCounter > 0 || GetStyle(ControlStyles.CacheText);
            }
            set {
 
                // if this control always cachest text or the handle hasn't been created,
                // just bail.
                //
                if (GetStyle(ControlStyles.CacheText) || !IsHandleCreated) {
                    return;
                }
 
                // otherwise, get the state and update the cache if necessary.
                //
                bool found;
                int cacheTextCounter = Properties.GetInteger(PropCacheTextCount, out found);                
                
                if (value) {
                    if (cacheTextCounter == 0) {
                        Properties.SetObject(PropCacheTextField, text);
                        if (text == null)  {
                            text = WindowText;
                        }                        
                    }
                    cacheTextCounter++;
                }
                else {
                    cacheTextCounter--;
                    if (cacheTextCounter == 0) {
                        text = (string)Properties.GetObject(PropCacheTextField, out found);
                    }
                }                
                Properties.SetInteger(PropCacheTextCount, cacheTextCounter);
            }                
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.CheckForIllegalCrossThreadCalls"]/*' />
        [ Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
          SRDescription(SR.ControlCheckForIllegalCrossThreadCalls),
          DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        ]
        public static bool CheckForIllegalCrossThreadCalls {
            get { return checkForIllegalCrossThreadCalls; }
            set { checkForIllegalCrossThreadCalls = value; }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.ClientRectangle"]/*' />
        /// <devdoc>
        ///     The client rect of the control.
        /// </devdoc>
        [
        Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRCategory(SR.CatLayout),
        SRDescription(SR.ControlClientRectangleDescr)
        ]
        public Rectangle ClientRectangle {
            get {
                return new Rectangle(0, 0, clientWidth, clientHeight);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.ClientSize"]/*' />
        /// <devdoc>
        ///     The size of the clientRect.
        /// </devdoc>
        [
        SRCategory(SR.CatLayout),
        Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlClientSizeDescr)
        ]
        public Size ClientSize {
            get {
                return new Size(clientWidth, clientHeight);
            }
 
            set {
                SetClientSizeCore(value.Width, value.Height);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.ClientSizeChanged"]/*' />
        /// <devdoc>
        ///    Fired when ClientSize changes.
        /// </devdoc>
        [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ControlOnClientSizeChangedDescr)]
        public event EventHandler ClientSizeChanged {
            add {
                Events.AddHandler(EventClientSize, value);
            }
            remove {
                Events.RemoveHandler(EventClientSize, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.CompanyName"]/*' />
        /// <devdoc>
        ///     Retrieves the company name of this specific component.
        /// </devdoc>
        [
        Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        DescriptionAttribute(SR.ControlCompanyNameDescr)
        ]
        public string CompanyName {
            [ResourceExposure(ResourceScope.Machine)]
            [ResourceConsumption(ResourceScope.Machine)]
            get {
                return VersionInfo.CompanyName;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.ContainsFocus"]/*' />
        /// <devdoc>
        ///    <para>Indicates whether the control or one of its children currently has the system
        ///       focus. This property is read-only.</para>
        /// </devdoc>
        [
        Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlContainsFocusDescr)
        ]
        public bool ContainsFocus {
            get {
                if (!IsHandleCreated) {
                    return false;
                }
 
                IntPtr focusHwnd = UnsafeNativeMethods.GetFocus();
 
                if (focusHwnd == IntPtr.Zero) {
                    return false;
                }       
 
                if (focusHwnd == this.Handle) {
                    return true;
                }
 
                if (UnsafeNativeMethods.IsChild(new HandleRef(this, this.Handle), new HandleRef(this, focusHwnd))) {
                    return true;
                }
 
                return false;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.ContextMenu"]/*' />
        /// <devdoc>
        ///     The contextMenu associated with this control. The contextMenu
        ///     will be shown when the user right clicks the mouse on the control.
        ///
        ///     Whidbey: ContextMenu is browsable false.  In all cases where both a context menu
        ///     and a context menu strip are assigned, context menu will be shown instead of context menu strip.
        /// </devdoc>
        [
        SRCategory(SR.CatBehavior),
        DefaultValue(null),
        SRDescription(SR.ControlContextMenuDescr),
        Browsable(false)
        ]
        public virtual ContextMenu ContextMenu {
            get {
                return (ContextMenu)Properties.GetObject(PropContextMenu);
            }
            set {
                ContextMenu oldValue = (ContextMenu)Properties.GetObject(PropContextMenu);
 
                if (oldValue != value) {
                    EventHandler disposedHandler = new EventHandler(DetachContextMenu);
 
                    if (oldValue != null) {
                        oldValue.Disposed -= disposedHandler;
                    }
 
                    Properties.SetObject(PropContextMenu, value);
 
                    if (value != null) {
                        value.Disposed += disposedHandler;
                    }
 
                    OnContextMenuChanged(EventArgs.Empty);
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.ContextMenuChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [
        SRCategory(SR.CatPropertyChanged),
        SRDescription(SR.ControlOnContextMenuChangedDescr),
        Browsable(false)
        ]
        public event EventHandler ContextMenuChanged {
            add {
                Events.AddHandler(EventContextMenu, value);
            }
            remove {
                Events.RemoveHandler(EventContextMenu, value);
            }
        }
 
 
       /// <include file='doc\Control.uex' path='docs/doc[@for="Control.ContextMenu"]/*' />
       /// <devdoc>
       ///     The contextMenuStrip associated with this control. The contextMenuStrip
       ///     will be shown when the user right clicks the mouse on the control.
       ///     Note: if a context menu is also assigned, it will take precidence over this property.
       /// </devdoc>
        [
        SRCategory(SR.CatBehavior),
        DefaultValue(null),
        SRDescription(SR.ControlContextMenuDescr)
        ]
        public virtual ContextMenuStrip ContextMenuStrip {
            get {
                 return (ContextMenuStrip)Properties.GetObject(PropContextMenuStrip);
             }
             set {
                 ContextMenuStrip oldValue = Properties.GetObject(PropContextMenuStrip) as ContextMenuStrip;
 
                 if (oldValue != value) {
                     EventHandler disposedHandler = new EventHandler(DetachContextMenuStrip);
 
                     if (oldValue != null) {
                         oldValue.Disposed -= disposedHandler;
                     }
 
                     Properties.SetObject(PropContextMenuStrip, value);
 
                     if (value != null) {
                         value.Disposed += disposedHandler;
                     }
 
                     OnContextMenuStripChanged(EventArgs.Empty);
                 }
             }
 
        }
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.ContextMenuStripChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ControlContextMenuStripChangedDescr)]
        public event EventHandler ContextMenuStripChanged {
            add {
                Events.AddHandler(EventContextMenuStrip, value);
            }
            remove {
                Events.RemoveHandler(EventContextMenuStrip, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Controls"]/*' />
        /// <devdoc>
        ///     Collection of child controls.
        /// </devdoc>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
        SRDescription(SR.ControlControlsDescr)
        ]
        public ControlCollection Controls {
            get {
                ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection);
 
                if (controlsCollection == null) {
                    controlsCollection = CreateControlsInstance();
                    Properties.SetObject(PropControlsCollection, controlsCollection);
                }
                return controlsCollection;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Created"]/*' />
        /// <devdoc>
        ///    <para>Indicates whether the control has been created. This property is read-only.</para>
        /// </devdoc>
        [
        Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlCreatedDescr)
        ]
        public bool Created {
            get {
                return(state & STATE_CREATED) != 0;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.CreateParams"]/*' />
        /// <devdoc>
        ///     Returns the CreateParams used to create the handle for this control.
        ///     Inheriting classes should call base.CreateParams in the manor
        ///     below:
        /// </devdoc>
        protected virtual CreateParams CreateParams {
            [
                SecurityPermission(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode),
                SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)
            ]
            get {
 
                // CLR4.0 or later, comctl32.dll needs to be loaded explicitly.
                if (needToLoadComCtl) {
                    if ((UnsafeNativeMethods.GetModuleHandle(ExternDll.Comctl32) != IntPtr.Zero)
                        || (UnsafeNativeMethods.LoadLibraryFromSystemPathIfAvailable(ExternDll.Comctl32) != IntPtr.Zero)) {
                        needToLoadComCtl = false;
                    } else {
                        int lastWin32Error = Marshal.GetLastWin32Error();
                        throw new Win32Exception(lastWin32Error, SR.GetString(SR.LoadDLLError, ExternDll.Comctl32));
                    }
                }
 
                // In a typical control this is accessed ten times to create and show a control.
                // It is a net memory savings, then, to maintain a copy on control.
                //
                if (createParams == null) {
                    createParams = new CreateParams();
                }
 
                CreateParams cp = createParams;
                cp.Style = 0;
                cp.ExStyle = 0;
                cp.ClassStyle = 0;
                cp.Caption = text;
 
                cp.X = x;
                cp.Y = y;
                cp.Width = width;
                cp.Height = height;
 
                cp.Style = NativeMethods.WS_CLIPCHILDREN;
                if (GetStyle(ControlStyles.ContainerControl)) {
                    cp.ExStyle |= NativeMethods.WS_EX_CONTROLPARENT;
                }
                cp.ClassStyle = NativeMethods.CS_DBLCLKS;
 
                if ((state & STATE_TOPLEVEL) == 0) {
                    // When the window is actually created, we will parent WS_CHILD windows to the
                    // parking form if cp.parent == 0.
                    //
                    cp.Parent = parent == null ? IntPtr.Zero : parent.InternalHandle;
                    cp.Style |= NativeMethods.WS_CHILD | NativeMethods.WS_CLIPSIBLINGS;
                }
                else {
                    cp.Parent = IntPtr.Zero;
                }
 
                if ((state & STATE_TABSTOP) != 0) cp.Style |= NativeMethods.WS_TABSTOP;
                if ((state & STATE_VISIBLE) != 0) cp.Style |= NativeMethods.WS_VISIBLE;
 
                // Unlike Visible, Windows doesn't correctly inherit disabledness from its parent -- an enabled child
                // of a disabled parent will look enabled but not get mouse events
                if (!Enabled) cp.Style |= NativeMethods.WS_DISABLED;
 
                // If we are being hosted as an Ax control, try to prevent the parking window
                // from being created by pre-filling the window handle here.
                //
                if (cp.Parent == IntPtr.Zero && IsActiveX) {
                    cp.Parent = ActiveXHWNDParent;
                }
 
                // Set Rtl bits
                if (RightToLeft == RightToLeft.Yes) {
                    cp.ExStyle |= NativeMethods.WS_EX_RTLREADING;
                    cp.ExStyle |= NativeMethods.WS_EX_RIGHT;
                    cp.ExStyle |= NativeMethods.WS_EX_LEFTSCROLLBAR;
                }
 
                return cp;
            }
        }
 
        internal virtual void NotifyValidationResult(object sender, CancelEventArgs ev) {
            this.ValidationCancelled = ev.Cancel ;
        }
 
        /// <devdoc>
        ///     Helper method...
        ///
        ///     Triggers validation on the active control, and returns bool indicating whether that control was valid.
        ///
        ///     The correct way to do this is to find the common ancestor of the active control and this control,
        ///     then request validation to be performed by that common container control.
        ///
        ///     Used by controls that don't participate in the normal enter/leave/validation process, but which
        ///     want to force form-level validation to occur before they attempt some important action.
        /// </devdoc>
        internal bool ValidateActiveControl(out bool validatedControlAllowsFocusChange) {
            bool valid = true;
            validatedControlAllowsFocusChange = false;
            IContainerControl c = GetContainerControlInternal();
            if (c != null && this.CausesValidation) {
                ContainerControl container = c as ContainerControl;
                if (container != null) {
                    while (container.ActiveControl == null) {
                        ContainerControl cc;
                        Control parent = container.ParentInternal;
                        if (parent != null) {
                            cc = parent.GetContainerControlInternal() as ContainerControl;
                            if (cc != null) {
                                container = cc;
                            }
                            else {
                                break;
                            }
                        }
                        else {
                            break;
                        }
                    }
 
                    valid = container.ValidateInternal(true, out validatedControlAllowsFocusChange);
                }
            }
 
            return valid;
        }
 
        internal bool ValidationCancelled {
            set {
                SetState(STATE_VALIDATIONCANCELLED, value);
            }
            get {
                if (GetState(STATE_VALIDATIONCANCELLED)) {
                    return true;
                }
                else {
                    Control parent = this.ParentInternal;
                    if (parent != null) {
                        return parent.ValidationCancelled;
                    }
 
                    return false;
                }
            }
        }
 
        /// <devdoc>
        ///     returns bool indicating whether the Top MDI Window is closing.
        ///     This property is set in the MDI children in WmClose method in form.cs when the top window is closing.
        ///     This property will be used in ActiveControl to determine if we want to skip set focus and window handle re-creation for the control.
        /// </devdoc>
        /// <internalonly/>
        internal bool IsTopMdiWindowClosing {
            set {
                SetState2(STATE2_TOPMDIWINDOWCLOSING, value);
            }
            get {
                return GetState2(STATE2_TOPMDIWINDOWCLOSING);
            }
        }
 
        /// <devdoc>
        ///     returns bool indicating whether the control is currently being scaled.
        ///     This property is set in ScaleControl method to allow method being called to condition code that should not run for scaling.
        /// </devdoc>
        /// <internalonly/>
        internal bool IsCurrentlyBeingScaled {
            private set {
                SetState2(STATE2_CURRENTLYBEINGSCALED, value);
            }
            get {
                return GetState2(STATE2_CURRENTLYBEINGSCALED);
            }
        }
 
        /// <devdoc>
        ///     Retrieves the Win32 thread ID of the thread that created the
        ///     handle for this control.  If the control's handle hasn't been
        ///     created yet, this method will return the current thread's ID.
        /// </devdoc>
        /// <internalonly/>
        internal int CreateThreadId {
            [ResourceExposure(ResourceScope.Process)]
            [ResourceConsumption(ResourceScope.Process)]
            get {
                if (IsHandleCreated) {
                    int pid;
                    return SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(this, Handle), out pid);
                }
                else {
                    return SafeNativeMethods.GetCurrentThreadId();
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Cursor"]/*' />
        /// <devdoc>
        ///     Retrieves the cursor that will be displayed when the mouse is over this
        ///     control.
        /// </devdoc>
        [
        SRCategory(SR.CatAppearance),
        SRDescription(SR.ControlCursorDescr),
        AmbientValue(null)
        ]
        public virtual Cursor Cursor {
            get {
                if (GetState(STATE_USEWAITCURSOR))
                {
                    return Cursors.WaitCursor;
                }
 
                Cursor cursor = (Cursor)Properties.GetObject(PropCursor);
                if (cursor != null) {
                    return cursor;
                }
 
                // We only do ambients for things with "Cursors.Default"
                // as their default.
                //
                Cursor localDefault = DefaultCursor;
                if (localDefault != Cursors.Default) {
                    return localDefault;
                }
 
                Control p = ParentInternal;
                if (p != null) {
                    return p.Cursor;
                }
 
                AmbientProperties ambient = AmbientPropertiesService;
                if (ambient != null && ambient.Cursor != null)
                    return ambient.Cursor;
 
                return localDefault;
            }
            set {
 
                Cursor localCursor = (Cursor)Properties.GetObject(PropCursor);
                Cursor resolvedCursor = Cursor;
                if (localCursor != value) {
                    Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "ModifyCursor Demanded");
                    IntSecurity.ModifyCursor.Demand();
 
                    Properties.SetObject(PropCursor, value);
                }
 
                // Other things can change the cursor... we
                // really want to force the correct cursor always...
                //
                if (IsHandleCreated) {
                    // We want to instantly change the cursor if the mouse is within our bounds.
                    // This includes the case where the mouse is over one of our children
                    NativeMethods.POINT p = new NativeMethods.POINT();
                    NativeMethods.RECT r = new NativeMethods.RECT();
                    UnsafeNativeMethods.GetCursorPos(p);
                    UnsafeNativeMethods.GetWindowRect(new HandleRef(this, Handle), ref r);
 
                    if ((r.left <= p.x && p.x < r.right && r.top <= p.y && p.y < r.bottom) || UnsafeNativeMethods.GetCapture() == Handle)
                        SendMessage(NativeMethods.WM_SETCURSOR, Handle, (IntPtr)NativeMethods.HTCLIENT);
                }
 
                if (!resolvedCursor.Equals(value)) {
                    OnCursorChanged(EventArgs.Empty);
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.CursorChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ControlOnCursorChangedDescr)]
        public event EventHandler CursorChanged {
            add {
                Events.AddHandler(EventCursor, value);
            }
            remove {
                Events.RemoveHandler(EventCursor, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.DataBindings"]/*' />
        /// <devdoc>
        ///     Retrieves the bindings for this control.
        /// </devdoc>
        [
        DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
        SRCategory(SR.CatData),
        SRDescription(SR.ControlBindingsDescr),
        RefreshProperties(RefreshProperties.All),
        ParenthesizePropertyName(true)
        ]
        public ControlBindingsCollection DataBindings
        {
            get
            {
                ControlBindingsCollection bindings = (ControlBindingsCollection)Properties.GetObject(PropBindings);
                if (bindings == null)
                {
                    bindings = new ControlBindingsCollection(this);
                    Properties.SetObject(PropBindings, bindings);
                }
                return bindings;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.DefaultBackColor"]/*' />
        /// <devdoc>
        ///     The default BackColor of a generic top-level Control.  Subclasses may have
        ///     different defaults.
        /// </devdoc>
        public static Color DefaultBackColor {
            get { return SystemColors.Control;}
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.DefaultCursor"]/*' />
        /// <devdoc>
        ///     Deriving classes can override this to configure a default cursor for their control.
        ///     This is more efficient than setting the cursor in the control's constructor,
        ///     and gives automatic support for ShouldSerialize and Reset in the designer.
        /// </devdoc>
        protected virtual Cursor DefaultCursor {
            get {
                return Cursors.Default;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.DefaultFont"]/*' />
        /// <devdoc>
        ///     The default Font of a generic top-level Control.  Subclasses may have
        ///     different defaults.
        /// </devdoc>
        public static Font DefaultFont {
            [ResourceExposure(ResourceScope.None)]
            [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
            get {
                if (defaultFont == null) {
                    defaultFont = SystemFonts.DefaultFont;
                    Debug.Assert(defaultFont != null, "defaultFont wasn't set!");
                }
 
                return defaultFont;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.DefaultForeColor"]/*' />
        /// <devdoc>
        ///     The default ForeColor of a generic top-level Control.  Subclasses may have
        ///     different defaults.
        /// </devdoc>
        public static Color DefaultForeColor {
            get { return SystemColors.ControlText;}
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.DefaultMargin"]/*' />
        protected virtual Padding DefaultMargin {
            get { return CommonProperties.DefaultMargin; }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.DefaultMaximumSize"]/*' />
        protected virtual Size DefaultMaximumSize {
            get { return CommonProperties.DefaultMaximumSize; }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.DefaultMinimumSize"]/*' />
        protected virtual Size DefaultMinimumSize {
            get { return CommonProperties.DefaultMinimumSize; }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.DefaultPadding"]/*' />
        protected virtual Padding DefaultPadding {
            get { return Padding.Empty; }
        }
 
        private RightToLeft DefaultRightToLeft {
            get { return RightToLeft.No; }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.DefaultSize"]/*' />
        /// <devdoc>
        ///     Deriving classes can override this to configure a default size for their control.
        ///     This is more efficient than setting the size in the control's constructor.
        /// </devdoc>
        protected virtual Size DefaultSize {
            get { return Size.Empty; }
        }
 
        private void DetachContextMenu(object sender, EventArgs e) {
            ContextMenu = null;
        }
 
 
        private void DetachContextMenuStrip(object sender, EventArgs e) {
            ContextMenuStrip = null;
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.DeviceDpi"]/*' />
        /// <devdoc>
        ///  DPI value either for the primary screen or for the monitor where the top-level parent is displayed when
        ///  EnableDpiChangedMessageHandling option is on and the application is per-monitor V2 DPI-aware (rs2+)
        /// </devdoc>
        [
            Browsable(false), // don't show in property browser
            EditorBrowsable(EditorBrowsableState.Always), // do show in the intellisense
            DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) // do not serialize
        ]
        public int DeviceDpi {
            get {
                if (DpiHelper.EnableDpiChangedMessageHandling) {
                    return deviceDpi;
                } 
                return DpiHelper.DeviceDpi;
            }
        }
        
        // The color to use when drawing disabled text.  Normally we use BackColor,
        // but that obviously won't work if we're transparent.
        internal Color DisabledColor {
            get {
                Color color = BackColor;
                if (color.A == 0) {
                    Control control = ParentInternal;
                    while (color.A == 0) {
                        if (control == null) {
                            // Don't know what to do, this seems good as anything
                            color = SystemColors.Control;
                            break;
                        }
                        color = control.BackColor;
                        control = control.ParentInternal;
                    }
                }
                return color;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.DisplayRectangle"]/*' />
        /// <devdoc>
        ///     Returns the client rect of the display area of the control.
        ///     For the base control class, this is identical to getClientRect.
        ///     However, inheriting controls may want to change this if their client
        ///     area differs from their display area.
        /// </devdoc>
        [
        Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlDisplayRectangleDescr)
        ]
        public virtual Rectangle DisplayRectangle {
            [SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces")]
            get {
                return new Rectangle(0, 0, clientWidth, clientHeight);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Disposed"]/*' />
        /// <devdoc>
        ///    <para>Indicates whether the control has been disposed. This
        ///       property is read-only.</para>
        /// </devdoc>
        [
        Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlDisposedDescr)
        ]
        public bool IsDisposed {
            get {
                return GetState(STATE_DISPOSED);
            }
        }
 
        /// <devdoc>
        ///     Disposes of the currently selected font handle (if cached).
        /// </devdoc>
        private void DisposeFontHandle() {
            if (Properties.ContainsObject(PropFontHandleWrapper)) {
                FontHandleWrapper fontHandle = Properties.GetObject(PropFontHandleWrapper) as FontHandleWrapper;
                if( fontHandle != null ){
                    fontHandle.Dispose();
                }
                Properties.SetObject(PropFontHandleWrapper, null);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Disposing"]/*' />
        /// <devdoc>
        ///    <para>Indicates whether the control is in the process of being disposed. This
        ///       property is read-only.</para>
        /// </devdoc>
        [
        Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlDisposingDescr)
        ]
        public bool Disposing {
            get {
                return GetState(STATE_DISPOSING);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Dock"]/*' />
        /// <devdoc>
        ///     The dock property. The dock property controls to which edge
        ///     of the container this control is docked to. For example, when docked to
        ///     the top of the container, the control will be displayed flush at the
        ///     top of the container, extending the length of the container.
        /// </devdoc>
        [
        SRCategory(SR.CatLayout),
        Localizable(true),
        RefreshProperties(RefreshProperties.Repaint),
        DefaultValue(CommonProperties.DefaultDock),
        SRDescription(SR.ControlDockDescr)
        ]
        public virtual DockStyle Dock {
            get {
                return DefaultLayout.GetDock(this);
            }
            set {
                if(value != Dock) {                        // NDPWhidbey 29434
#if DEBUG
                    int dbgLayoutCheck = LayoutSuspendCount;
#endif
                    SuspendLayout();
                    try {
                        DefaultLayout.SetDock(this, value);
                        OnDockChanged(EventArgs.Empty);
                    } finally {
                        ResumeLayout();
                    }
#if DEBUG
                    AssertLayoutSuspendCount(dbgLayoutCheck);
#endif
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.DockChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ControlOnDockChangedDescr)]
        public event EventHandler DockChanged {
            add {
                Events.AddHandler(EventDock, value);
            }
            remove {
                Events.RemoveHandler(EventDock, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.DoubleBuffered"]/*' />
        /// <devdoc>
        ///    <para>This will enable or disable double buffering.</para>
        /// </devdoc>
        [
        SRCategory(SR.CatBehavior),
        SRDescription(SR.ControlDoubleBufferedDescr)
        ]
        protected virtual bool DoubleBuffered {
            get {
                return GetStyle(ControlStyles.OptimizedDoubleBuffer);
            }
            set {
                if (value != DoubleBuffered) {
                    
                    if (value) {
                        SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, value);
                    }
                    else {
                        SetStyle(ControlStyles.OptimizedDoubleBuffer, value);
                    }
                }
            }
        }
 
        private bool DoubleBufferingEnabled {
            get {                                
#pragma warning disable 618            
                return GetStyle(ControlStyles.DoubleBuffer | ControlStyles.UserPaint);
#pragma warning restore 618
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Enabled"]/*' />
        /// <devdoc>
        ///    <para>Indicates whether the control is currently enabled.</para>
        /// </devdoc>
        [
        SRCategory(SR.CatBehavior),
        Localizable(true),
        DispId(NativeMethods.ActiveX.DISPID_ENABLED),
        SRDescription(SR.ControlEnabledDescr)
        ]
        public bool Enabled {
            get {
                // We are only enabled if our parent is enabled
                if (!GetState(STATE_ENABLED))
                    return false;
                else if (ParentInternal == null)
                    return true;
                else
                    return ParentInternal.Enabled;
            }
 
            set {
                bool oldValue = Enabled;
                SetState(STATE_ENABLED, value);
 
                if (oldValue != value) {
                    if (!value) {
                        SelectNextIfFocused();
                    }
 
                    OnEnabledChanged(EventArgs.Empty);
                }
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.EnabledChanged"]/*' />
        /// <devdoc>
        ///    <para>Occurs when the control is enabled.</para>
        /// </devdoc>
        [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ControlOnEnabledChangedDescr)]
        public event EventHandler EnabledChanged {
            add {
                Events.AddHandler(EventEnabled, value);
            }
            remove {
                Events.RemoveHandler(EventEnabled, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Focused"]/*' />
        /// <devdoc>
        ///    <para>Indicates whether the control has focus. This property is read-only.</para>
        /// </devdoc>
        [
        Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlFocusedDescr)
        ]
        public virtual bool Focused {
            get {
                return IsHandleCreated && UnsafeNativeMethods.GetFocus() == Handle;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Font"]/*' />
        /// <devdoc>
        ///     Retrieves the current font for this control. This will be the font used
        ///     by default for painting and text in the control.
        /// </devdoc>
        [
        SRCategory(SR.CatAppearance),
        Localizable(true),
        DispId(NativeMethods.ActiveX.DISPID_FONT),
        AmbientValue(null),
        SRDescription(SR.ControlFontDescr)
        ]
        public virtual Font Font {
            [return : MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(ActiveXFontMarshaler))]
            [ResourceExposure(ResourceScope.None)]
            [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
            get {
                Font font = (Font)Properties.GetObject(PropFont);
                if (font != null) {
                    return font;
                }
 
                Font f = GetParentFont();
                if (f != null) {
                    return f;
                }
 
                if (IsActiveX) {
                    f = ActiveXAmbientFont;
                    if (f != null) {
                        return f;
                    }
                }
 
                AmbientProperties ambient = AmbientPropertiesService;
                if (ambient != null && ambient.Font != null) {
                    return ambient.Font;
                }
 
                return DefaultFont;
            }
            [param : MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(ActiveXFontMarshaler))]
            set {
                Font local = (Font)Properties.GetObject(PropFont);
                Font resolved = Font;
 
                bool localChanged = false;
                if (value == null) {
                    if (local != null) {
                        localChanged = true;
                    }
                }
                else {
                    if (local == null) {
                        localChanged = true;
                    }
                    else {
                        localChanged = !value.Equals(local);
                    }
                }
 
                if (localChanged) {
                    // Store new local value
                    //
                    Properties.SetObject(PropFont, value);
 
                    // We only fire the Changed event if the "resolved" value
                    // changed, however we must update the font if the local
                    // value changed...
                    //
                    if (!resolved.Equals(value)) {
                        // Cleanup any font handle wrapper...
                        //
                        DisposeFontHandle();
 
                        if (Properties.ContainsInteger(PropFontHeight)) {
                            Properties.SetInteger(PropFontHeight, (value == null) ? -1 : value.Height);
                        }
 
                        // Font is an ambient property.  We need to layout our parent because Font may
                        // change our size.  We need to layout ourselves because our children may change
                        // size by inheriting the new value.
                        //
                        using(new LayoutTransaction(ParentInternal, this, PropertyNames.Font)) {
                            OnFontChanged(EventArgs.Empty);
                        }
                    }
                    else {
                        if (IsHandleCreated && !GetStyle(ControlStyles.UserPaint)) {
                            DisposeFontHandle();
                            SetWindowFont();
                        }
                    }
                }
            }
        }
 
        internal void ScaleFont(float factor) {
            Font local = (Font)Properties.GetObject(PropFont);
            Font resolved = Font;
            Font newFont = DpiHelper.EnableDpiChangedHighDpiImprovements ?
                                new Font(this.Font.FontFamily, this.Font.Size * factor, this.Font.Style, this.Font.Unit, this.Font.GdiCharSet, this.Font.GdiVerticalFont) :
                                new Font(this.Font.FontFamily, this.Font.Size * factor, this.Font.Style);
 
            if  ((local == null) || !local.Equals(newFont)) {
                Properties.SetObject(PropFont, newFont);
 
                if (!resolved.Equals(newFont)) {
                    DisposeFontHandle();
 
                    if (Properties.ContainsInteger(PropFontHeight)) {
                        Properties.SetInteger(PropFontHeight, newFont.Height);
                    }
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.FontChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ControlOnFontChangedDescr)]
        public event EventHandler FontChanged {
            add {
                Events.AddHandler(EventFont, value);
            }
            remove {
                Events.RemoveHandler(EventFont, value);
            }
        }
 
        internal IntPtr FontHandle {
            get {
                Font font = (Font)Properties.GetObject(PropFont);
 
                if (font != null) {
                    FontHandleWrapper fontHandle = (FontHandleWrapper)Properties.GetObject(PropFontHandleWrapper);
                    if (fontHandle == null) {
                        fontHandle = new FontHandleWrapper(font);
 
                        Properties.SetObject(PropFontHandleWrapper, fontHandle);
                    }
 
                    return fontHandle.Handle;
                }
 
                if (parent != null) {
                    return parent.FontHandle;
                }
 
                AmbientProperties ambient = AmbientPropertiesService;
 
                if (ambient != null && ambient.Font != null) {
 
                    FontHandleWrapper fontHandle = null;
 
                    Font currentAmbient = (Font)Properties.GetObject(PropCurrentAmbientFont);
 
                    if (currentAmbient != null && currentAmbient == ambient.Font) {
                        fontHandle = (FontHandleWrapper)Properties.GetObject(PropFontHandleWrapper);
                    }
                    else {
                        Properties.SetObject(PropCurrentAmbientFont, ambient.Font);
                    }
 
                    if (fontHandle == null) {
                        font =  ambient.Font;
                        fontHandle = new FontHandleWrapper(font);
 
                        Properties.SetObject(PropFontHandleWrapper, fontHandle);
                    }
 
                    return fontHandle.Handle;
                }
 
                return GetDefaultFontHandleWrapper().Handle;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.FontHeight"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected int FontHeight {
            get {
                bool found;
                int fontHeight = Properties.GetInteger(PropFontHeight, out found);
                if (found && fontHeight != -1) {
                    return fontHeight;
                }
                else {
                    Font font = (Font)Properties.GetObject(PropFont);
                    if (font != null) {
                        fontHeight = font.Height;
                        Properties.SetInteger(PropFontHeight, fontHeight);
                        return fontHeight;
                    }
                }
 
                //ask the parent if it has the font height
                int localFontHeight = -1;
 
                if (ParentInternal != null && ParentInternal.CanAccessProperties) {
                    localFontHeight = ParentInternal.FontHeight;
                }
 
                //if we still have a bad value, then get the actual font height
                if (localFontHeight == -1) {
                    localFontHeight = Font.Height;
                    Properties.SetInteger(PropFontHeight, localFontHeight);
                }
 
                return localFontHeight;
            }
            set {
                Properties.SetInteger(PropFontHeight, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.ForeColor"]/*' />
        /// <devdoc>
        ///     The foreground color of the control.
        /// </devdoc>
        [
        SRCategory(SR.CatAppearance),
        DispId(NativeMethods.ActiveX.DISPID_FORECOLOR),
        SRDescription(SR.ControlForeColorDescr)
        ]
        public virtual Color ForeColor {
            get {
                Color color = Properties.GetColor(PropForeColor);
                if (!color.IsEmpty) {
                    return color;
                }
 
                Control p = ParentInternal;
                if (p != null && p.CanAccessProperties) {
                    return p.ForeColor;
                }
 
                Color c = Color.Empty;
 
                if (IsActiveX) {
                    c = ActiveXAmbientForeColor;
                }
 
                if (c.IsEmpty) {
                    AmbientProperties ambient = AmbientPropertiesService;
                    if (ambient != null)
                        c = ambient.ForeColor;
                }
 
                if (!c.IsEmpty)
                    return c;
                else
                    return DefaultForeColor;
            }
 
            set {
                Color c = ForeColor;
                if (!value.IsEmpty || Properties.ContainsObject(PropForeColor)) {
                    Properties.SetColor(PropForeColor, value);
                }
                if (!c.Equals(ForeColor)) {
                    OnForeColorChanged(EventArgs.Empty);
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.ForeColorChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ControlOnForeColorChangedDescr)]
        public event EventHandler ForeColorChanged {
            add {
                Events.AddHandler(EventForeColor, value);
            }
            remove {
                Events.RemoveHandler(EventForeColor, value);
            }
        }
 
        private Font GetParentFont() {
            if (ParentInternal != null && ParentInternal.CanAccessProperties)
                return ParentInternal.Font;
            else
                return null;
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.GetPreferredSize"]/*' />
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        [SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces")]
        public virtual Size GetPreferredSize(Size proposedSize) {
            Size prefSize;
 
            if (GetState(STATE_DISPOSING| STATE_DISPOSED)) {
                // if someone's asking when we're disposing just return what we last had.
                prefSize = CommonProperties.xGetPreferredSizeCache(this);
            }
            else {
                 // Switch Size.Empty to maximum possible values
                proposedSize = LayoutUtils.ConvertZeroToUnbounded(proposedSize);
 
                // Force proposedSize to be within the elements constraints.  (This applies
                // minimumSize, maximumSize, etc.)
                proposedSize = ApplySizeConstraints(proposedSize);
                if (GetState2(STATE2_USEPREFERREDSIZECACHE)) {
                    Size cachedSize = CommonProperties.xGetPreferredSizeCache(this);
 
                    // If the "default" preferred size is being requested, and we have a cached value for it, return it.
                    // 
                    if(!cachedSize.IsEmpty && (proposedSize == LayoutUtils.MaxSize)) {
       
#if DEBUG
#if DEBUG_PREFERREDSIZE
                            Size newPreferredSize = ApplySizeConstraints(GetPreferredSizeCore(proposedSize));
                            bool cacheHitCorrect = (cachedSize == newPreferredSize);
                            if (!cacheHitCorrect && !GetAnyDisposingInHierarchy()) {
                                Debug.Fail(
                                      "Cached PreferredSize " + cachedSize.ToString() 
                                      + " did not match computed: " +newPreferredSize.ToString() 
                                      +". Did we forget to invalidate the cache?\r\n\r\nControl Information: " + WindowsFormsUtils.AssertControlInformation(cacheHitCorrect, this)
                                      + "\r\nChanged Properties\r\n " + CommonProperties.Debug_GetChangedProperties(this));                        
                            }
#endif                      
#endif
                            return cachedSize;
                    }
                }
            
              
 
                CacheTextInternal = true;
                try {
                    prefSize = GetPreferredSizeCore(proposedSize);
                }
                finally {
                    CacheTextInternal = false;
                }
              
                // There is no guarantee that GetPreferredSizeCore() return something within
                // proposedSize, so we apply the element's constraints again.
                prefSize = ApplySizeConstraints(prefSize);
 
                // If the "default" preferred size was requested, cache the computed value.
                // 
                if(GetState2(STATE2_USEPREFERREDSIZECACHE) && proposedSize == LayoutUtils.MaxSize) {
                    CommonProperties.xSetPreferredSizeCache(this, prefSize);
                }
            }
            return prefSize;
        }
 
        // Overriding this method allows us to get the caching and clamping the proposedSize/output to
        // MinimumSize / MaximumSize from GetPreferredSize for free.
        internal virtual Size GetPreferredSizeCore(Size proposedSize) {
            return CommonProperties.GetSpecifiedBounds(this).Size;
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Handle"]/*' />
        /// <devdoc>
        ///     The HWND handle that this control is bound to. If the handle
        ///     has not yet been created, this will force handle creation.
        /// </devdoc>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        DispId(NativeMethods.ActiveX.DISPID_HWND),
        SRDescription(SR.ControlHandleDescr)
        ]
        public IntPtr Handle {
            get {
                if (checkForIllegalCrossThreadCalls &&
                    !inCrossThreadSafeCall &&
                    InvokeRequired) {
                    throw new InvalidOperationException(SR.GetString(SR.IllegalCrossThreadCall,
                                                                     Name));
                }
 
                if (!IsHandleCreated)
                {
                    CreateHandle();
                }
 
                return HandleInternal;
            }
        }
 
        internal IntPtr HandleInternal {
            get {
                return window.Handle;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.HasChildren"]/*' />
        /// <devdoc>
        ///     True if this control has child controls in its collection.  This
        ///     is more efficient than checking for Controls.Count > 0, but has the
        ///     same effect.
        /// </devdoc>
        [
        Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlHasChildrenDescr)
        ]
        public bool HasChildren {
            get {
                ControlCollection controls = (ControlCollection)Properties.GetObject(PropControlsCollection);
                return controls != null && controls.Count > 0;
            }
        }
 
        internal virtual bool HasMenu {
            get {
                return false;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Height"]/*' />
        /// <devdoc>
        ///     The height of this control
        /// </devdoc>
        [
        SRCategory(SR.CatLayout),
        Browsable(false), EditorBrowsable(EditorBrowsableState.Always),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlHeightDescr)
        ]
        public int Height {
            get {
                return height;
            }
            set{
                SetBounds(x, y, width, value, BoundsSpecified.Height);
            }
        }
 
        internal bool HostedInWin32DialogManager {
            get {
                if (!GetState(STATE_CHECKEDHOST)) {
                    Control topMost = TopMostParent;
                    if (this != topMost) {
                        SetState(STATE_HOSTEDINDIALOG, topMost.HostedInWin32DialogManager);
                    }
                    else {
                        IntPtr parentHandle = UnsafeNativeMethods.GetParent(new HandleRef(this, Handle));
                        IntPtr lastParentHandle = parentHandle;
 
                        StringBuilder sb = new StringBuilder(32);
 
                        SetState(STATE_HOSTEDINDIALOG, false);
 
                        while (parentHandle != IntPtr.Zero) {
                            int len = UnsafeNativeMethods.GetClassName(new HandleRef(null, lastParentHandle), null, 0);
                            if (len > sb.Capacity) {
                                sb.Capacity = len + 5;
                            }
                            UnsafeNativeMethods.GetClassName(new HandleRef(null, lastParentHandle), sb, sb.Capacity);
 
                            if (sb.ToString() == "#32770") {
                                SetState(STATE_HOSTEDINDIALOG, true);
                                break;
                            }
 
                            lastParentHandle = parentHandle;
                            parentHandle = UnsafeNativeMethods.GetParent(new HandleRef(null, parentHandle));
                        }
                    }
 
                    SetState(STATE_CHECKEDHOST, true);
 
                }
 
                return GetState(STATE_HOSTEDINDIALOG);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.IsHandleCreated"]/*' />
        /// <devdoc>
        ///     Whether or not this control has a handle associated with it.
        /// </devdoc>
        [
        Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlHandleCreatedDescr)
        ]
        public bool IsHandleCreated {
            get { return window.Handle != IntPtr.Zero; }
        }
 
        /// <devdoc>
        ///     Determines if layout is currently suspended.
        /// </devdoc>
        internal bool IsLayoutSuspended {
            get {
                return layoutSuspendCount > 0;
            }
        }
 
        internal bool IsWindowObscured {
            get {
                if (!IsHandleCreated || !Visible) {
                    return false;
                }
 
                bool emptyRegion = false;
 
                NativeMethods.RECT temp = new NativeMethods.RECT();
                Region working;
                Control parent = ParentInternal;
                if (parent != null) {
                    while (parent.ParentInternal != null ) {
                        parent = parent.ParentInternal;
                    }
                }
 
                UnsafeNativeMethods.GetWindowRect(new HandleRef(this, Handle), ref temp);
                working = new Region(Rectangle.FromLTRB(temp.left, temp.top, temp.right, temp.bottom));
 
                try {
                    IntPtr prev;
                    IntPtr next;
                    IntPtr start;
                    if (parent != null) {
                        start = parent.Handle;
                    }
                    else {
                        start = Handle;
                    }
 
                    for (prev = start;
                         (next = UnsafeNativeMethods.GetWindow(new HandleRef(null, prev), NativeMethods.GW_HWNDPREV)) != IntPtr.Zero;
                         prev = next) {
 
                        UnsafeNativeMethods.GetWindowRect(new HandleRef(null, next), ref temp);
                        Rectangle current = Rectangle.FromLTRB(temp.left, temp.top, temp.right, temp.bottom);
 
                        if (SafeNativeMethods.IsWindowVisible(new HandleRef(null, next))) {
                            working.Exclude(current);
                        }
                    }
 
 
                    Graphics g = CreateGraphics();
                    try {
                        emptyRegion = working.IsEmpty(g);
                    }
                    finally {
                        g.Dispose();
                    }
                }
                finally {
                    working.Dispose();
                }
 
                return emptyRegion;
            }
        }
 
        /// <devdoc>
        ///     Returns the current value of the handle. This may be zero if the handle
        ///     has not been created.
        /// </devdoc>
        internal IntPtr InternalHandle {
            get {
                if (!IsHandleCreated)
                {
                    return IntPtr.Zero;
                }
                else
                {
                    return Handle;
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.InvokeRequired"]/*' />
        /// <devdoc>
        ///     Determines if the caller must call invoke when making method
        ///     calls to this control.  Controls in windows forms are bound to a specific thread,
        ///     and are not thread safe.  Therefore, if you are calling a control's method
        ///     from a different thread, you must use the control's invoke method
        ///     to marshal the call to the proper thread.  This function can be used to
        ///     determine if you must call invoke, which can be handy if you don't know
        ///     what thread owns a control.
        ///
        ///     There are five functions on a control that are safe to call from any
        ///     thread:  GetInvokeRequired, Invoke, BeginInvoke, EndInvoke and
        ///     CreateGraphics.  For all other method calls, you should use one of the
        ///     invoke methods.
        /// </devdoc>
        [
        Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlInvokeRequiredDescr)
        ]
        public bool InvokeRequired {
            get {
 
                using (new MultithreadSafeCallScope())
                {
                    HandleRef hwnd;
                    if (IsHandleCreated) {
                        hwnd = new HandleRef(this, Handle);
                    }
                    else {
                        Control marshalingControl = FindMarshalingControl();
 
                        if (!marshalingControl.IsHandleCreated) {
                            return false;
                        }
 
                        hwnd = new HandleRef(marshalingControl, marshalingControl.Handle);
                    }
 
                    int pid;
                    int hwndThread = SafeNativeMethods.GetWindowThreadProcessId(hwnd, out pid);
                    int currentThread = SafeNativeMethods.GetCurrentThreadId();
                    return(hwndThread != currentThread);
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.IsAccessible"]/*' />
        /// <devdoc>
        ///      Indicates whether or not this control is an accessible control
        ///      i.e. whether it should be visible to accessibility applications.
        /// </devdoc>
        [
        SRCategory(SR.CatBehavior),
        Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlIsAccessibleDescr)
        ]
        public bool IsAccessible {
            get {
                return GetState(STATE_ISACCESSIBLE);
            }
            set {
                SetState(STATE_ISACCESSIBLE, value);
            }
        }
 
        /// <devdoc>
        ///     Used to tell if this control is being hosted as an ActiveX control.
        /// </devdoc>
        internal bool IsActiveX {
            get {
                return GetState2(STATE2_ISACTIVEX);
            }
        }
 
        // VsWhidbey 434959 : If the control on which GetContainerControl( ) is called is a ContainerControl, then we dont return the parent 
        // but return the same control. This is Everett behavior so we cannot change this since this would be a breaking change.
        // Hence we have a new internal property IsContainerControl which returns false for all Everett control, but 
        // this property is overidden in SplitContainer to return true so that we skip the SplitContainer 
        // and the correct Parent ContainerControl is returned by GetContainerControl().
        internal virtual bool IsContainerControl
        {
            get
            {
                return false;
            }
        }
 
        /// <devdoc>
        ///     Used to tell if this control is being hosted in IE.
        /// </devdoc>
        internal bool IsIEParent {
            get {
                return IsActiveX ? ActiveXInstance.IsIE : false;
            }
        }
 
        /// <devdoc>
        ///     Used to tell if the control is mirrored
        ///     Don't call this from CreateParams. Will lead to nasty problems
        ///     since we might call CreateParams here - you dig!
        /// </devdoc>
        [
        SRCategory(SR.CatLayout),        
        Browsable(false),
        EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.IsMirroredDescr)        
        ]
        public bool IsMirrored {
            get {
                if (!IsHandleCreated) {
                    CreateParams cp = CreateParams;
                    SetState(STATE_MIRRORED, (cp.ExStyle & NativeMethods.WS_EX_LAYOUTRTL) != 0);
                }
                return GetState(STATE_MIRRORED);
            }
        }
 
        /// <devdoc>
        ///     Specifies whether the control is willing to process mnemonics when hosted in an container ActiveX (Ax Sourcing).
        /// </devdoc>
        internal virtual bool IsMnemonicsListenerAxSourced
        {
            get
            {
                return false;
            }
        }
        
        /// <devdoc>
        ///     Used to tell if this BackColor is Supported
        /// </devdoc>
        private bool IsValidBackColor (Color c){
           if (!c.IsEmpty && !GetStyle(ControlStyles.SupportsTransparentBackColor) && c.A < 255)
           {
                return false;
           }
           return true;
 
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Left"]/*' />
        /// <devdoc>
        ///     The left coordinate of this control.
        /// </devdoc>
        [
        SRCategory(SR.CatLayout),
        Browsable(false), EditorBrowsable(EditorBrowsableState.Always),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlLeftDescr)
        ]
        public int Left {
            get {
                return x;
            }
            set {
                SetBounds(value, y, width, height, BoundsSpecified.X);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Location"]/*' />
        /// <devdoc>
        ///     The location of this control.
        /// </devdoc>
        [
        SRCategory(SR.CatLayout),
        Localizable(true),
        SRDescription(SR.ControlLocationDescr)
        ]
        public Point Location {
            get {
                return new Point(x, y);
            }
            set {
                SetBounds(value.X, value.Y, width, height, BoundsSpecified.Location);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.LocationChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ControlOnLocationChangedDescr)]
        public event EventHandler LocationChanged {
            add {
                Events.AddHandler(EventLocation, value);
            }
            remove {
                Events.RemoveHandler(EventLocation, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Margin"]/*' />
        [
        SRDescription(SR.ControlMarginDescr),
        SRCategory(SR.CatLayout),
        Localizable(true)
        ]
        public Padding Margin
        {
            get { return CommonProperties.GetMargin(this); }
            set
            {
                // This should be done here rather than in the property store as
                // some IArrangedElements actually support negative padding.
                value = LayoutUtils.ClampNegativePaddingToZero(value);
 
                // SetMargin causes a layout as a side effect.
                if (value != Margin)
                {
                    CommonProperties.SetMargin(this, value);
                    OnMarginChanged(EventArgs.Empty);
                }
                Debug.Assert(Margin == value, "Error detected while setting Margin.");
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.MarginChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatLayout), SRDescription(SR.ControlOnMarginChangedDescr)]
        public event EventHandler MarginChanged
        {
            add
            {
                Events.AddHandler(EventMarginChanged, value);
            }
            remove
            {
                Events.RemoveHandler(EventMarginChanged, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.MaximumSize"]/*' />
        [SRCategory(SR.CatLayout)]
        [Localizable(true)]
        [SRDescription(SR.ControlMaximumSizeDescr)]
        [AmbientValue(typeof(Size), "0, 0")]
        public virtual Size MaximumSize {
            get { return CommonProperties.GetMaximumSize(this, DefaultMaximumSize); }
            set {
                if (value == Size.Empty) {
                    CommonProperties.ClearMaximumSize(this);
                    Debug.Assert(MaximumSize == DefaultMaximumSize, "Error detected while resetting MaximumSize.");
                }
                else if (value != MaximumSize) {
                    // SetMaximumSize causes a layout as a side effect.
                    CommonProperties.SetMaximumSize(this, value);
                    Debug.Assert(MaximumSize == value, "Error detected while setting MaximumSize.");
                }
 
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.MinimumSize"]/*' />
        [SRCategory(SR.CatLayout)]
        [Localizable(true)]
        [SRDescription(SR.ControlMinimumSizeDescr)]
        public virtual Size MinimumSize {
            get { return CommonProperties.GetMinimumSize(this, DefaultMinimumSize); }
            set {
                if (value != MinimumSize) {
                    // SetMinimumSize causes a layout as a side effect.
                    CommonProperties.SetMinimumSize(this, value);
                }
                Debug.Assert(MinimumSize == value, "Error detected while setting MinimumSize.");
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.ModifierKeys"]/*' />
        /// <devdoc>
        ///     Retrieves the current state of the modifier keys. This will check the
        ///     current state of the shift, control, and alt keys.
        /// </devdoc>
        public static Keys ModifierKeys {
            get {
                Keys modifiers = 0;
                // SECURITYNOTE : only let state of Shift-Control-Alt out...
                //
                if (UnsafeNativeMethods.GetKeyState((int)Keys.ShiftKey) < 0) modifiers |= Keys.Shift;
                if (UnsafeNativeMethods.GetKeyState((int)Keys.ControlKey) < 0) modifiers |= Keys.Control;
                if (UnsafeNativeMethods.GetKeyState((int)Keys.Menu) < 0) modifiers |= Keys.Alt;
                return modifiers;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.MouseButtons"]/*' />
        /// <devdoc>
        ///     The current state of the mouse buttons. This will check the
        ///     current state of the left, right, and middle mouse buttons.
        /// </devdoc>
        public static MouseButtons MouseButtons {
            get {
                MouseButtons buttons = (MouseButtons)0;
                // SECURITYNOTE : only let state of MouseButtons out...
                //
                if (UnsafeNativeMethods.GetKeyState((int)Keys.LButton) < 0) buttons |= MouseButtons.Left;
                if (UnsafeNativeMethods.GetKeyState((int)Keys.RButton) < 0) buttons |= MouseButtons.Right;
                if (UnsafeNativeMethods.GetKeyState((int)Keys.MButton) < 0) buttons |= MouseButtons.Middle;
                if (UnsafeNativeMethods.GetKeyState((int)Keys.XButton1) < 0) buttons |= MouseButtons.XButton1;
                if (UnsafeNativeMethods.GetKeyState((int)Keys.XButton2) < 0) buttons |= MouseButtons.XButton2;
                return buttons;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.MousePosition"]/*' />
        /// <devdoc>
        ///     The current position of the mouse in screen coordinates.
        /// </devdoc>
        public static Point MousePosition {
            get {
                // Reviewed: The following demand has always been commented out since v1.0. In Whidbey, we have
                // re-reviewed this method to see if it needs protection, but haven't found any threats, so are
                // going to keep it this way. See VSWhidbey #427555 for details.
                //
                // Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "ScreenLocationOfThings Demanded");
                // IntSecurity.ScreenLocationOfThings.Demand();
 
                NativeMethods.POINT pt = new NativeMethods.POINT();
                UnsafeNativeMethods.GetCursorPos(pt);
                return new Point(pt.x, pt.y);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Name"]/*' />
        /// <devdoc>
        ///     Name of this control. The designer will set this to the same
        ///     as the programatic Id "(name)" of the control.  The name can be
        ///     used as a key into the ControlCollection.
        /// </devdoc>
        [Browsable(false)]
        public string Name {
            get {
                string name = (string)Properties.GetObject(PropName);
                if (String.IsNullOrEmpty(name)) {
                    if (Site != null) {
                        name = Site.Name;
                    }
 
                    if (name == null) {
                        name = "";
                    }
                }
 
                return name;
            }
            set {
                if (String.IsNullOrEmpty(value)) {
                    Properties.SetObject(PropName, null);
                }
                else {
                    Properties.SetObject(PropName, value);
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Parent"]/*' />
        /// <devdoc>
        ///     The parent of this control.
        /// </devdoc>
        [
        SRCategory(SR.CatBehavior),
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlParentDescr)
        ]
        public Control Parent {
            get {
                Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "GetParent Demanded");
                IntSecurity.GetParent.Demand();
 
                return ParentInternal;
            }
            set {
                ParentInternal = value;
            }
        }
 
        // SECURITY WARNING: This property bypasses a security demand. Use with caution!
        internal virtual Control ParentInternal {
            get {
                return parent;
            }
            set {
                if (parent != value) {
                    if (value != null) {
                        value.Controls.Add(this);
                    }
                    else {
                        parent.Controls.Remove(this);
                    }
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.ProductName"]/*' />
        /// <devdoc>
        ///     Retrieves the product name of this specific component.
        /// </devdoc>
        [
        Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlProductNameDescr)
        ]
        public string ProductName {
            [ResourceExposure(ResourceScope.Machine)]
            [ResourceConsumption(ResourceScope.Machine)]
            get {
                return VersionInfo.ProductName;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.ProductVersion"]/*' />
        /// <devdoc>
        ///     Retrieves the product version of this specific component.
        /// </devdoc>
        [
        Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlProductVersionDescr)
        ]
        public string ProductVersion {
            [ResourceExposure(ResourceScope.Machine)]
            [ResourceConsumption(ResourceScope.Machine)]
            get {
                return VersionInfo.ProductVersion;
            }
        }
 
        /// <devdoc>
        ///     Retrieves our internal property storage object. If you have a property
        ///     whose value is not always set, you should store it in here to save
        ///     space.
        /// </devdoc>
        internal PropertyStore Properties {
            get {
                return propertyStore;
            }
        }
 
        // Returns the value of the backColor field -- no asking the parent with its color is, etc.
        internal Color RawBackColor {
            get {
                return Properties.GetColor(PropBackColor);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.RecreatingHandle"]/*' />
        /// <devdoc>
        ///    <para>Indicates whether the control is currently recreating its handle. This
        ///       property is read-only.</para>
        /// </devdoc>
        [
        SRCategory(SR.CatBehavior),
        Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlRecreatingHandleDescr)
        ]
        public bool RecreatingHandle {
            get {
                return(state & STATE_RECREATE) != 0;
            }
        }
 
        internal virtual void AddReflectChild() {
        }
 
        internal virtual void RemoveReflectChild() {
        }
 
        private Control ReflectParent {
            get {
                return reflectParent;
            }
            set {
                if (value != null) {
                    value.AddReflectChild();
                }
 
                Control c = ReflectParent as Control;
                reflectParent = value;
                if (c != null) {
                    c.RemoveReflectChild();
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Region"]/*' />
        /// <devdoc>
        ///     The Region associated with this control.  (defines the
        ///     outline/silhouette/boundary of control)
        /// </devdoc>
        [
        SRCategory(SR.CatLayout),
        Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlRegionDescr)
        ]
        public Region Region {
            get {
                return (Region)Properties.GetObject(PropRegion);
            }
            set {
                if (GetState(STATE_TOPLEVEL)) {
                    Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "ChangeWindowRegion Demanded");
                    IntSecurity.ChangeWindowRegionForTopLevel.Demand();
                }
 
                Region oldRegion = Region;
                if (oldRegion != value) {
                    Properties.SetObject(PropRegion, value);
 
                    if (oldRegion != null) {
                        oldRegion.Dispose();
                    }
 
                    if (IsHandleCreated) {
                        IntPtr regionHandle = IntPtr.Zero;
 
                        try {
                            if (value != null) {
                                regionHandle = GetHRgn(value);
                            }
 
                            if (IsActiveX) {
                                regionHandle = ActiveXMergeRegion(regionHandle);
                            }
 
                            if (UnsafeNativeMethods.SetWindowRgn(new HandleRef(this, Handle), new HandleRef(this, regionHandle), SafeNativeMethods.IsWindowVisible(new HandleRef(this, Handle))) != 0) {
                                //The Hwnd owns the region.
                                regionHandle = IntPtr.Zero;
                            }
                        }
                        finally {
                            if (regionHandle != IntPtr.Zero) {
                                SafeNativeMethods.DeleteObject(new HandleRef(null, regionHandle));
                            }
                        }
                    }
 
                    OnRegionChanged(EventArgs.Empty);
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.RegionChanged"]/*' />
        /// <devdoc>
        ///     Event fired when the value of Region property is changed on Control
        /// </devdoc>
        [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ControlRegionChangedDescr)]
        public event EventHandler RegionChanged {
            add {
               Events.AddHandler(EventRegionChanged, value);
            }
            remove {
                Events.RemoveHandler(EventRegionChanged, value);
            }
        }
 
        // Helper function for Rtl
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.RenderRightToLeft"]/*' />
        /// <internalonly/>
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [Obsolete("This property has been deprecated. Please use RightToLeft instead. http://go.microsoft.com/fwlink/?linkid=14202")]
        protected internal bool RenderRightToLeft
        {
            get {
                return true;
            }
        }
 
        /// <devdoc>
        ///     Determines if the parent's background will be rendered on the label control.
        /// </devdoc>
        internal bool RenderTransparent {
            get {
                return GetStyle(ControlStyles.SupportsTransparentBackColor) && this.BackColor.A < 255;
            }
        }
 
        /// <devdoc>
        /// </devdoc>
        private bool RenderColorTransparent(Color c) {
            return GetStyle(ControlStyles.SupportsTransparentBackColor) && c.A < 255;
        }
 
 
        /// <devdoc>
        /// Refer VsWhidbey : 440669: This property is required by certain controls (TabPage) to render its transparency using theming API.
        /// We dont want all controls (that are have transparent BackColor) to use theming API to render its background because it has  HUGE PERF cost.
        /// </devdoc>
        /// <internalonly/>
        internal virtual bool RenderTransparencyWithVisualStyles {
            get {
                return false;
            }
        }
 
        /// <devdoc>
        ///     Represents the bounds of the control that need to be scaled.  Control bounds
        ///     need to be scaled until ScaleControl is called.  They need to be scaled again
        ///     if their bounds change after ScaleControl is called.
        /// </devdoc>
        internal BoundsSpecified RequiredScaling {
            get {
                if ((requiredScaling & RequiredScalingEnabledMask) != 0) {
                    return (BoundsSpecified)(requiredScaling & RequiredScalingMask);
                }
                return BoundsSpecified.None;
            }
            set {
                byte enableBit = (byte)(requiredScaling & RequiredScalingEnabledMask);
                requiredScaling = (byte)(((int)value & RequiredScalingMask) | enableBit);
            }
        }
 
        /// <devdoc>
        ///     Determines if the required scaling property is enabled.  If not,
        ///     RequiredScaling always returns None.
        /// </devdoc>
        internal bool RequiredScalingEnabled {
            get {
                return (requiredScaling & RequiredScalingEnabledMask) != 0;
            }
            set {
                byte scaling = (byte)(requiredScaling & RequiredScalingMask);
                requiredScaling = scaling;
                if (value) requiredScaling |= RequiredScalingEnabledMask;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.ResizeRedraw"]/*' />
        /// <devdoc>
        ///     Indicates whether the control should redraw itself when resized.
        /// </devdoc>
        [
        SRDescription(SR.ControlResizeRedrawDescr)
        ]
        protected bool ResizeRedraw {
            get {
                return GetStyle( ControlStyles.ResizeRedraw );
            }
            set {
                SetStyle( ControlStyles.ResizeRedraw, value );
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Right"]/*' />
        /// <devdoc>
        ///    <para>The right coordinate of the control.</para>
        /// </devdoc>
        [
        SRCategory(SR.CatLayout),
        Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlRightDescr)
        ]
        public int Right {
            get {
                return x + width;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.RightToLeft"]/*' />
        /// <devdoc>
        ///     This is used for international applications where the language
        ///     is written from RightToLeft. When this property is true,
        ///     control placement and text will be from right to left.
        /// </devdoc>
        [
        SRCategory(SR.CatAppearance),
        Localizable(true),
        AmbientValue(RightToLeft.Inherit),
        SRDescription(SR.ControlRightToLeftDescr)
        ]
        public virtual RightToLeft RightToLeft {
            get {
                bool found;
                int rightToLeft = Properties.GetInteger(PropRightToLeft, out found);
                if (!found) {
                    rightToLeft = (int)RightToLeft.Inherit;
                }
 
                if (((RightToLeft)rightToLeft) == RightToLeft.Inherit) {
                    Control parent = ParentInternal;
                    if (parent != null) {
                        rightToLeft = (int)parent.RightToLeft;
                    }
                    else {
                        rightToLeft = (int)DefaultRightToLeft;
                    }
                }
                return (RightToLeft)rightToLeft;
            }
 
            set {
                //valid values are 0x0 to 0x2.
                if (!ClientUtils.IsEnumValid(value, (int)value, (int)RightToLeft.No, (int)RightToLeft.Inherit)){
                    throw new InvalidEnumArgumentException("RightToLeft", (int)value, typeof(RightToLeft));
                }
 
                RightToLeft oldValue = RightToLeft;
 
                if (Properties.ContainsInteger(PropRightToLeft) || value != RightToLeft.Inherit) {
                    Properties.SetInteger(PropRightToLeft, (int)value);
                }
 
                if (oldValue != RightToLeft) {
                    // Setting RTL on a container does not cause the container to change size.
                    // Only the children need to have thier layout updated.
                    using(new LayoutTransaction(this, this, PropertyNames.RightToLeft)) {
                        OnRightToLeftChanged(EventArgs.Empty);
                    }
                }
            }
            }
 
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.RightToLeftChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ControlOnRightToLeftChangedDescr)]
        public event EventHandler RightToLeftChanged {
            add {
                Events.AddHandler(EventRightToLeft, value);
            }
            remove {
                Events.RemoveHandler(EventRightToLeft, value);
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.ScaleChildren"]/*' />
        /// <devdoc>
        ///     This property controls the scaling of child controls.  If true child controls
        ///     will be scaled when the Scale method on this control is called.  If false,
        ///     child controls will not be scaled.  The default is true, and you must override
        ///     this property to provide a different value.
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual bool ScaleChildren {
            get {
                return true;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Site"]/*' />
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        public override ISite Site {
            get {
                return base.Site;
            }
            set {
                AmbientProperties oldAmbients = AmbientPropertiesService;
                AmbientProperties newAmbients = null;
 
                if (value != null) {
                    newAmbients = (AmbientProperties)value.GetService(typeof(AmbientProperties));
                }
 
 
                // If the ambients changed, compare each property.
                //
                if (oldAmbients != newAmbients) {
                    bool checkFont = !Properties.ContainsObject(PropFont);
                    bool checkBackColor = !Properties.ContainsObject(PropBackColor);
                    bool checkForeColor = !Properties.ContainsObject(PropForeColor);
                    bool checkCursor = !Properties.ContainsObject(PropCursor);
 
                    Font oldFont = null;
                    Color oldBackColor = Color.Empty;
                    Color oldForeColor = Color.Empty;
                    Cursor oldCursor = null;
 
                    if (checkFont) {
                        oldFont = Font;
                    }
 
                    if (checkBackColor) {
                        oldBackColor = BackColor;
                    }
 
                    if (checkForeColor) {
                        oldForeColor = ForeColor;
                    }
 
                    if (checkCursor) {
                        oldCursor = Cursor;
                    }
 
                    Properties.SetObject(PropAmbientPropertiesService, newAmbients);
                    base.Site = value;
 
                    if (checkFont && !oldFont.Equals(Font)) {
                        OnFontChanged(EventArgs.Empty);
                    }
                    if (checkForeColor && !oldForeColor.Equals(ForeColor)) {
                        OnForeColorChanged(EventArgs.Empty);
                    }
                    if (checkBackColor && !oldBackColor.Equals(BackColor)) {
                        OnBackColorChanged(EventArgs.Empty);
                    }
                    if (checkCursor && oldCursor.Equals(Cursor)) {
                        OnCursorChanged(EventArgs.Empty);
                    }
                }
                else {
                    // If the ambients haven't changed, we just set a new site.
                    //
                    base.Site = value;
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Size"]/*' />
        /// <devdoc>
        ///    <para>The size of the control.</para>
        /// </devdoc>
        [
        SRCategory(SR.CatLayout),
        Localizable(true),
        SRDescription(SR.ControlSizeDescr)
        ]
        public Size Size {
            get {
                return new Size(width, height);
            }
            set {
                SetBounds(x, y, value.Width, value.Height, BoundsSpecified.Size);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.SizeChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ControlOnSizeChangedDescr)]
        public event EventHandler SizeChanged {
            add {
                Events.AddHandler(EventSize, value);
            }
            remove {
                Events.RemoveHandler(EventSize, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.TabIndex"]/*' />
        /// <devdoc>
        ///    <para>
        ///       The tab index of
        ///       this control.</para>
        /// </devdoc>
        [
        SRCategory(SR.CatBehavior),
        Localizable(true),
        MergableProperty(false),
        SRDescription(SR.ControlTabIndexDescr)
        ]
        public int TabIndex {
            get {
                return tabIndex == -1 ? 0 : tabIndex;
            }
            set {
                if (value < 0) {
                    throw new ArgumentOutOfRangeException("TabIndex", SR.GetString(SR.InvalidLowBoundArgumentEx, "TabIndex", value.ToString(CultureInfo.CurrentCulture), (0).ToString(CultureInfo.CurrentCulture)));
                }
 
                if (tabIndex != value) {
                    tabIndex = value;
                    OnTabIndexChanged(EventArgs.Empty);
                }
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.TabIndexChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ControlOnTabIndexChangedDescr)]
        public event EventHandler TabIndexChanged {
            add {
                Events.AddHandler(EventTabIndex, value);
            }
            remove {
                Events.RemoveHandler(EventTabIndex, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.TabStop"]/*' />
        /// <devdoc>
        ///    <para>Indicates whether the user can give the focus to this control using the TAB
        ///       key. This property is read-only.</para>
        /// </devdoc>
        [
        SRCategory(SR.CatBehavior),
        DefaultValue(true),
        DispId(NativeMethods.ActiveX.DISPID_TABSTOP),
        SRDescription(SR.ControlTabStopDescr)
        ]
        public bool TabStop {
            get {
                return TabStopInternal;
            }
            set {
                if (TabStop != value) {
                    TabStopInternal = value;
                    if (IsHandleCreated) SetWindowStyle(NativeMethods.WS_TABSTOP, value);
                    OnTabStopChanged(EventArgs.Empty);
                }
            }
        }
 
        // Grab out the logical of setting TABSTOP state, so that derived class could use this.
        internal bool TabStopInternal {
            get {
                return (state & STATE_TABSTOP) != 0;
            }
            set {
                if (TabStopInternal != value) {
                    SetState(STATE_TABSTOP, value);
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.TabStopChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ControlOnTabStopChangedDescr)]
        public event EventHandler TabStopChanged {
            add {
                Events.AddHandler(EventTabStop, value);
            }
            remove {
                Events.RemoveHandler(EventTabStop, value);
            }
        }
 
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Tag"]/*' />
        [
        SRCategory(SR.CatData),
        Localizable(false),
        Bindable(true),
        SRDescription(SR.ControlTagDescr),
        DefaultValue(null),
        TypeConverter(typeof(StringConverter)),
        ]
        public object Tag {
            get {
                return Properties.GetObject(PropUserData);
            }
            set {
                Properties.SetObject(PropUserData, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Text"]/*' />
        /// <devdoc>
        ///     The current text associated with this control.
        /// </devdoc>
        [
        SRCategory(SR.CatAppearance),
        Localizable(true),
        Bindable(true),
        DispId(NativeMethods.ActiveX.DISPID_TEXT),
        SRDescription(SR.ControlTextDescr)
        ]
        public virtual string Text {
            get {
                if (CacheTextInternal) {
                    return(text == null) ? "" : text;
                }
                else {
                    return WindowText;
                }
            }
 
            set {
                if (value == null) {
                    value = "";
                }
 
                if (value == Text) {
                    return;
                }
 
                if (CacheTextInternal) {
                    text = value;
                }
                WindowText = value;
                OnTextChanged(EventArgs.Empty);
 
                if( this.IsMnemonicsListenerAxSourced ){
                    for( Control ctl = this; ctl != null; ctl = ctl.ParentInternal ) {
                        ActiveXImpl activeXImpl = (ActiveXImpl)ctl.Properties.GetObject(PropActiveXImpl);
                        if( activeXImpl != null ) {
                            activeXImpl.UpdateAccelTable();
                            break;
                        }
                    }
                }
               
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.TextChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ControlOnTextChangedDescr)]
        public event EventHandler TextChanged {
            add {
                Events.AddHandler(EventText, value);
            }
            remove {
                Events.RemoveHandler(EventText, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Top"]/*' />
        /// <devdoc>
        ///     Top coordinate of this control.
        /// </devdoc>
        [
        SRCategory(SR.CatLayout),
        Browsable(false), EditorBrowsable(EditorBrowsableState.Always),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlTopDescr)
        ]
        public int Top {
            get {
                return y;
            }
            set {
                SetBounds(x, value, width, height, BoundsSpecified.Y);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.TopLevelControl"]/*' />
        /// <devdoc>
        ///     The top level control that contains this control. This doesn't
        ///     have to be the same as the value returned from getForm since forms
        ///     can be parented to other controls.
        /// </devdoc>
        [
        SRCategory(SR.CatBehavior),
        Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlTopLevelControlDescr)
        ]
        public Control TopLevelControl {
            get {
                Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "GetParent Demanded");
                IntSecurity.GetParent.Demand();
                return TopLevelControlInternal;
            }
        }
 
        // SECURITY WARNING: This property bypasses a security demand. Use with caution!
        internal Control TopLevelControlInternal {
            get {
                Control control = this;
                while (control != null && !control.GetTopLevel()) {
                    control = control.ParentInternal;
                }
                return control;
            }
        }
 
        // SECURITY WARNING: This property bypasses a security demand. Use with caution!
        internal Control TopMostParent {
            get {
                Control control = this;
                while (control.ParentInternal != null) {
                    control = control.ParentInternal;
                }
                return control;
            }
        }
 
 
        private BufferedGraphicsContext BufferContext {
            get {
                //This auto upgraged v1 client to per-process doublebuffering logic
                //
                return BufferedGraphicsManager.Current;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.ShowKeyboardCues"]/*' />
        /// <devdoc>
        ///    <para>Indicates whether the user interface is in a state to show or hide keyboard
        ///       accelerators. This property is read-only.</para>
        /// </devdoc>
        [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        protected internal virtual bool ShowKeyboardCues {
            get {
                // Controls in design mode always draw their accellerators.
                if (!IsHandleCreated || DesignMode) {
                    return true;
                    // would be nice to query SystemParametersInfo, but have trouble
                    // getting this to work and this should not really be called before
                    // handle created anyway
                }
 
                // How this all works
                
                // uiCuesState contains this control's cached state of whether or not it thinks
                // accelerators/focus cues are turned on. the first 16 bits represent focus cues
                // the second represent keyboard cues.  "F" is the UISTATE_FOCUS_CUES_MASK, 
                // "F0" is the UISTATE_KEYBOARD_CUES_MASK
 
                // We check here if we have cached state.  If we dont, we need to initialize ourself.
                // We do this by checking "MenuAccessKeysUnderlined" - we show if this returns true.
 
                // If MenuAccessKeysUnderlined returns false, we have to manually call CHANGEUISTATE on the topmost control 
                // Why? Well the way the API seems to work is that it stores in a bit flag for the the hidden 
                // state.
 
                // Details from the Menu keydown to changed value of uiCuesState...
                
                // When someone does press the ALT (Menu)/F10 key we will
                //   Call ProcessUICues on the control that had focus at the time
                //          ProcessUICues will check the current state of the control using WM_QUERYUISTATE               
                //          If WM_QUERYUISTATE indicates that the accelerators are hidden we will 
                //                  either call WM_UPDATEUISTATE or WM_CHANGEUISTATE depending on whether we're hosted or not.
                //          All controls in the heirarchy will be individually called back on WM_UPDATEUISTATE, which will go into WmUpdateUIState.
                //   In WmUpdateUIState, we will update our uiCuesState cached value, which 
                //   changes the public value of what we return here for ShowKeyboardCues/ShowFocusCues.
 
                if ((uiCuesState & UISTATE_KEYBOARD_CUES_MASK) == 0) {
 
                        // VSWhidbey 362408 -- if we get in here that means this is the windows bug where the first top
                        // level window doesn't get notified with WM_UPDATEUISTATE
                        //
                        
                        if (SystemInformation.MenuAccessKeysUnderlined) {
                            uiCuesState |= UISTATE_KEYBOARD_CUES_SHOW;
                        }
                        else {
                            // if we're in the hidden state, we need to manufacture an update message so everyone knows it.
                            //
                            int actionMask = (NativeMethods.UISF_HIDEACCEL | 
                                (AccessibilityImprovements.Level1 ? 0 : NativeMethods.UISF_HIDEFOCUS)) << 16;
                            uiCuesState |= UISTATE_KEYBOARD_CUES_HIDDEN;
 
                            // The side effect of this initial state is that adding new controls may clear the accelerator
                            // state (has been this way forever)
                            UnsafeNativeMethods.SendMessage(new HandleRef(TopMostParent, TopMostParent.Handle),
                                    NativeMethods.WM_CHANGEUISTATE,
                                    (IntPtr)(actionMask | NativeMethods.UIS_SET),
                                    IntPtr.Zero);
                        }
                 }
                 return (uiCuesState & UISTATE_KEYBOARD_CUES_MASK) == UISTATE_KEYBOARD_CUES_SHOW;                
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.ShowFocusCues"]/*' />
        /// <devdoc>
        ///    <para>Indicates whether the user interface is in a state to show or hide focus
        ///       rectangles. This property is read-only.</para>
        /// </devdoc>
        [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        protected internal virtual bool ShowFocusCues {
            get {
                if (!IsHandleCreated) {
                    return true;
                    // would be nice to query SystemParametersInfo, but have trouble
                    // getting this to work and this should not really be called before
                    // handle created anyway
                }
 
                // See "How this all works" in ShowKeyboardCues
 
                if ((uiCuesState & UISTATE_FOCUS_CUES_MASK) == 0) {
                    // VSWhidbey 362408 -- if we get in here that means this is the windows bug where the first top
                    // level window doesn't get notified with WM_UPDATEUISTATE
                    //
                    if (SystemInformation.MenuAccessKeysUnderlined) {
                        uiCuesState |= UISTATE_FOCUS_CUES_SHOW;
                    }
                    else {
                        uiCuesState |= UISTATE_FOCUS_CUES_HIDDEN;
 
                        // if we're in the hidden state, we need to manufacture an update message so everyone knows it.
                        //
                        int actionMask = (NativeMethods.UISF_HIDEACCEL | NativeMethods.UISF_HIDEFOCUS) << 16;
 
                        // The side effect of this initial state is that adding new controls may clear the focus cue state
                        // state (has been this way forever)
                        UnsafeNativeMethods.SendMessage(new HandleRef(TopMostParent, TopMostParent.Handle),
                                NativeMethods.WM_CHANGEUISTATE,
                                (IntPtr)(actionMask | NativeMethods.UIS_SET),
                                IntPtr.Zero);
 
                    }
                }
                return (uiCuesState & UISTATE_FOCUS_CUES_MASK) == UISTATE_FOCUS_CUES_SHOW;
            }
        }
 
        // The parameter used in the call to ShowWindow for this control
        //
        internal virtual int ShowParams {
            get {
                return NativeMethods.SW_SHOW;
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.UseWaitCursor"]/*' />
        /// <devdoc>
        ///     When this property in true the Cursor Property is set to WaitCursor as well as the Cursor Property
        ///     of all the child controls.
        /// </devdoc>
        [
        DefaultValue(false),
        EditorBrowsable(EditorBrowsableState.Always),
        Browsable(true),
        SRCategory(SR.CatAppearance),
        SRDescription(SR.ControlUseWaitCursorDescr),
        ]
        public bool UseWaitCursor {
            get { return GetState(STATE_USEWAITCURSOR); }
            set {
                if (GetState(STATE_USEWAITCURSOR) != value) {
                    SetState(STATE_USEWAITCURSOR, value);
                    ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection);
 
                    if (controlsCollection != null) {
                        // PERFNOTE: This is more efficient than using Foreach.  Foreach
                        // forces the creation of an array subset enum each time we
                        // enumerate
                        for(int i = 0; i < controlsCollection.Count; i++) {
                            controlsCollection[i].UseWaitCursor = value;
                        }
                    }
                }
            }
        }
 
        /// <devdoc>
        ///     Determines whether to use compatible text rendering engine (GDI+) or not (GDI).
        ///     This property overwrites the UseCompatibleTextRenderingDefault switch when set programmatically.
        ///     Exposed publicly only by controls that support GDI text rendering (Label, LinkLabel and some others).
        ///     Observe that this property is NOT virtual (to allow for caching the property value - see LinkLabel)
        ///     and should be used by controls that support it only (see SupportsUseCompatibleTextRendering).
        /// </devdoc>
        internal bool UseCompatibleTextRenderingInt {
            get{
                if (Properties.ContainsInteger(PropUseCompatibleTextRendering)){
                    bool found;
                    int value = Properties.GetInteger(PropUseCompatibleTextRendering, out found);
                    if( found ){
                        return value == 1;
                    }
                }
 
                return Control.UseCompatibleTextRenderingDefault;
            }
            set{
                if( SupportsUseCompatibleTextRendering && UseCompatibleTextRenderingInt != value ){
                    Properties.SetInteger(PropUseCompatibleTextRendering, value ? 1 : 0);
                    // Update the preferred size cache since we will be rendering text using a different engine.
                    LayoutTransaction.DoLayoutIf(AutoSize, ParentInternal, this, PropertyNames.UseCompatibleTextRendering);
                    Invalidate();
                }
            }
        }
 
        /// <devdoc>
        ///     Determines whether the control supports rendering text using GDI+ and GDI.
        ///     This is provided for container controls (PropertyGrid) to iterate through its children to set 
        ///     UseCompatibleTextRendering to the same value if the child control supports it.
        /// </devdoc>
        internal virtual bool SupportsUseCompatibleTextRendering {
            get {
                return false;
            }
        }
 
        private ControlVersionInfo VersionInfo {
            get {
                ControlVersionInfo info = (ControlVersionInfo)Properties.GetObject(PropControlVersionInfo);
                if (info == null) {
                    info = new ControlVersionInfo(this);
                    Properties.SetObject(PropControlVersionInfo, info);
                }
                return info;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Visible"]/*' />
        /// <devdoc>
        ///    <para>Indicates whether the control is visible.</para>
        /// </devdoc>
        [
        SRCategory(SR.CatBehavior),
        Localizable(true),
        SRDescription(SR.ControlVisibleDescr)
        ]
        public bool Visible {
            get {
                return GetVisibleCore();
            }
            set {
                SetVisibleCore(value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.VisibleChanged"]/*' />
        /// <devdoc>
        ///    <para>Occurs when the control becomes visible.</para>
        /// </devdoc>
        [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ControlOnVisibleChangedDescr)]
        public event EventHandler VisibleChanged {
            add {
                Events.AddHandler(EventVisible, value);
            }
            remove {
                Events.RemoveHandler(EventVisible, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.WaitForWaitHandle"]/*' />
        /// <devdoc>
        ///     Wait for the wait handle to receive a signal: throw an exception if the thread is no longer with us.
        /// </devdoc>
        private void WaitForWaitHandle(WaitHandle waitHandle) {
            int threadId = CreateThreadId;
            Application.ThreadContext ctx = Application.ThreadContext.FromId(threadId);
            if (ctx == null) {
                // Couldn't find the thread context, so we don't know the state.  We shouldn't throw.
                return;
            }
            IntPtr threadHandle = ctx.GetHandle();
            bool processed = false;
            // setting default exitcode to 0, though it won't be accessed in current code below due to short-circuit logic in condition (returnValue will be false when exitCode is undefined)
            uint exitCode = 0;
            bool returnValue = false;
            while (!processed) {
                //Get the thread's exit code, if we found the thread as expected
                if (threadHandle != null) {
                    returnValue = UnsafeNativeMethods.GetExitCodeThread(threadHandle, out exitCode);
                }
                //If we didn't find the thread, or if GetExitCodeThread failed, we don't know the thread's state:
                //if we don't know, we shouldn't throw.
                if ((returnValue && exitCode != NativeMethods.STILL_ACTIVE) || 
                    (!returnValue && Marshal.GetLastWin32Error() == NativeMethods.ERROR_INVALID_HANDLE) ||
                    AppDomain.CurrentDomain.IsFinalizingForUnload()) {
                    if (waitHandle.WaitOne(1, false)) {
                        break;
                    }
                    throw new InvalidAsynchronousStateException(SR.GetString(SR.ThreadNoLongerValid));
                }
 
                //Dev10 Bug 600316, 905126: Because Control.Invoke() is not fully thread safe, so it is possible that
                //a ThreadMethodEntry can be sent to a control after it is disposed. In this case, we need to check
                //if there is any ThreadMethodEntry in the queue. If so, we need "complete" them.
                if (IsDisposed && threadCallbackList != null && threadCallbackList.Count > 0) {
                    lock (threadCallbackList) {
                        Exception ex = new System.ObjectDisposedException(GetType().Name);
                        while (threadCallbackList.Count > 0) {
                            ThreadMethodEntry entry = (ThreadMethodEntry)threadCallbackList.Dequeue();
                            entry.exception = ex;
                            entry.Complete();
                        }
                    }
                }
 
                processed = waitHandle.WaitOne(1000, false);
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Width"]/*' />
        /// <devdoc>
        ///     The width of this control.
        /// </devdoc>
        [
        SRCategory(SR.CatLayout),
        Browsable(false), EditorBrowsable(EditorBrowsableState.Always),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlWidthDescr)
        ]
        public int Width {
            get {
                return width;
            }
            set {
                SetBounds(x, y, value, height, BoundsSpecified.Width);
            }
        }
 
        /// <devdoc>
        ///     The current exStyle of the hWnd
        /// </devdoc>
        /// <internalonly/>
        private int WindowExStyle {
            get {
                return unchecked((int)(long)UnsafeNativeMethods.GetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_EXSTYLE));
            }
            set {
                UnsafeNativeMethods.SetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_EXSTYLE, new HandleRef(null, (IntPtr)value));
            }
        }
 
        /// <devdoc>
        ///     The current style of the hWnd
        /// </devdoc>
        /// <internalonly/>
        internal int WindowStyle {
            get {
                return unchecked((int)(long)UnsafeNativeMethods.GetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_STYLE));
            }
            set {
                UnsafeNativeMethods.SetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_STYLE, new HandleRef(null, (IntPtr)value));
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.WindowTarget"]/*' />
        /// <devdoc>
        ///     The target of Win32 window messages.
        /// </devdoc>
        /// <internalonly/>
        [
        SRCategory(SR.CatBehavior),
        Browsable(false), EditorBrowsable(EditorBrowsableState.Never),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ControlWindowTargetDescr)
        ]
        public IWindowTarget WindowTarget {
            [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
            get {
                return window.WindowTarget;
            }
            [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
            set {
                window.WindowTarget = value;
            }
        }
 
        /// <devdoc>
        ///     The current text of the Window; if the window has not yet been created, stores it in the control.
        ///     If the window has been created, stores the text in the underlying win32 control.
        ///     This property should be used whenever you want to get at the win32 control's text. For all other cases,
        ///     use the Text property - but note that this is overridable, and any of your code that uses it will use
        ///     the overridden version in controls that subclass your own.
        /// </devdoc>
        internal virtual string WindowText {
            get {
 
                if (!IsHandleCreated) {
                    if (text == null) {
                        return "";
                    }
                    else {
                        return text;
                    }
                }
 
                using (new MultithreadSafeCallScope()) {
 
                    // it's okay to call GetWindowText cross-thread.
                    //
 
                    int textLen = SafeNativeMethods.GetWindowTextLength(new HandleRef(window, Handle));
 
                    // Check to see if the system supports DBCS character
                    // if so, double the length of the buffer.
                    if (SystemInformation.DbcsEnabled) {
                        textLen = (textLen * 2) + 1;
                    }
                    StringBuilder sb = new StringBuilder(textLen + 1);
                    UnsafeNativeMethods.GetWindowText(new HandleRef(window, Handle), sb, sb.Capacity);
                    return sb.ToString();
                }
            }
            set {
                if (value == null) value = "";
                if (!WindowText.Equals(value)) {
                    if (IsHandleCreated) {
                        UnsafeNativeMethods.SetWindowText(new HandleRef(window, Handle), value);
                    }
                    else {
                        if (value.Length == 0) {
                            text = null;
                        }
                        else {
                            text = value;
                        }
                    }
                }
            }
        }
 
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Click"]/*' />
        /// <devdoc>
        ///    <para>Occurs when the control is clicked.</para>
        /// </devdoc>
        [SRCategory(SR.CatAction), SRDescription(SR.ControlOnClickDescr)]
        public event EventHandler Click {
            add {
                Events.AddHandler(EventClick, value);
            }
            remove {
                Events.RemoveHandler(EventClick, value);
            }
        }
 
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.ControlAdded"]/*' />
        /// <devdoc>
        ///    <para>Occurs when a new control is added.</para>
        /// </devdoc>
        [
        SRCategory(SR.CatBehavior),
        Browsable(true),
        EditorBrowsable(EditorBrowsableState.Advanced),
        SRDescription(SR.ControlOnControlAddedDescr)
        ]
        public event ControlEventHandler ControlAdded {
            add {
                Events.AddHandler(EventControlAdded, value);
            }
            remove {
                Events.RemoveHandler(EventControlAdded, value);
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.ControlRemoved"]/*' />
        /// <devdoc>
        ///    <para>Occurs when a control is removed.</para>
        /// </devdoc>
        [
        SRCategory(SR.CatBehavior),
        Browsable(true),
        EditorBrowsable(EditorBrowsableState.Advanced),
        SRDescription(SR.ControlOnControlRemovedDescr)
        ]
        public event ControlEventHandler ControlRemoved {
            add {
                Events.AddHandler(EventControlRemoved, value);
            }
            remove {
                Events.RemoveHandler(EventControlRemoved, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.DragDrop"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatDragDrop), SRDescription(SR.ControlOnDragDropDescr)]
        public event DragEventHandler DragDrop {
            add {
                Events.AddHandler(EventDragDrop, value);
            }
            remove {
                Events.RemoveHandler(EventDragDrop, value);
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.DragEnter"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatDragDrop), SRDescription(SR.ControlOnDragEnterDescr)]
        public event DragEventHandler DragEnter {
            add {
                Events.AddHandler(EventDragEnter, value);
            }
            remove {
                Events.RemoveHandler(EventDragEnter, value);
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.DragOver"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatDragDrop), SRDescription(SR.ControlOnDragOverDescr)]
        public event DragEventHandler DragOver {
            add {
                Events.AddHandler(EventDragOver, value);
            }
            remove {
                Events.RemoveHandler(EventDragOver, value);
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.DragLeave"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatDragDrop), SRDescription(SR.ControlOnDragLeaveDescr)]
        public event EventHandler DragLeave {
            add {
                Events.AddHandler(EventDragLeave, value);
            }
            remove {
                Events.RemoveHandler(EventDragLeave, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.GiveFeedback"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatDragDrop), SRDescription(SR.ControlOnGiveFeedbackDescr)]
        public event GiveFeedbackEventHandler GiveFeedback {
            add {
                Events.AddHandler(EventGiveFeedback, value);
            }
            remove {
                Events.RemoveHandler(EventGiveFeedback, value);
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.HandleCreated"]/*' />
        /// <devdoc>
        ///    <para>Occurs when a handle is created for the control.</para>
        /// </devdoc>
        [SRCategory(SR.CatPrivate), Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), SRDescription(SR.ControlOnCreateHandleDescr)]
        public event EventHandler HandleCreated {
            add {
                Events.AddHandler(EventHandleCreated, value);
            }
            remove {
                Events.RemoveHandler(EventHandleCreated, value);
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.HandleDestroyed"]/*' />
        /// <devdoc>
        ///    <para>Occurs when the control's handle is destroyed.</para>
        /// </devdoc>
        [SRCategory(SR.CatPrivate), Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), SRDescription(SR.ControlOnDestroyHandleDescr)]
        public event EventHandler HandleDestroyed {
            add {
                Events.AddHandler(EventHandleDestroyed, value);
            }
            remove {
                Events.RemoveHandler(EventHandleDestroyed, value);
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.HelpRequested"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatBehavior), SRDescription(SR.ControlOnHelpDescr)]
        public event HelpEventHandler HelpRequested {
            add {
                Events.AddHandler(EventHelpRequested, value);
            }
            remove {
                Events.RemoveHandler(EventHelpRequested, value);
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Invalidated"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatAppearance), Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), SRDescription(SR.ControlOnInvalidateDescr)]
        public event InvalidateEventHandler Invalidated {
            add {
                Events.AddHandler(EventInvalidated, value);
            }
            remove {
                Events.RemoveHandler(EventInvalidated, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.PreferredSize"]/*' />
        [Browsable(false)]
        public Size PreferredSize {
            get { return GetPreferredSize(Size.Empty); }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Padding"]/*' />
        [
        SRDescription(SR.ControlPaddingDescr),
        SRCategory(SR.CatLayout),
        Localizable(true)
        ]
        public Padding Padding {
            get { return CommonProperties.GetPadding(this, DefaultPadding); }
            set {
                if (value != Padding) {
                    CommonProperties.SetPadding(this, value);
                    // Ideally we are being laid out by a LayoutEngine that cares about our preferred size.
                    // We set our LAYOUTISDIRTY bit and ask our parent to refresh us.
                    SetState(STATE_LAYOUTISDIRTY, true);
                    using (new LayoutTransaction(ParentInternal, this, PropertyNames.Padding)) {
                        OnPaddingChanged(EventArgs.Empty);
                    }
 
                    if(GetState(STATE_LAYOUTISDIRTY)) {
                        // The above did not cause our layout to be refreshed.  We explicitly refresh our
                        // layout to ensure that any children are repositioned to account for the change
                        // in padding.
                       LayoutTransaction.DoLayout(this, this, PropertyNames.Padding);
                    }
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.PaddingChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatLayout), SRDescription(SR.ControlOnPaddingChangedDescr)]
        public event EventHandler PaddingChanged {
            add {
                Events.AddHandler(EventPaddingChanged, value);
            }
            remove {
                Events.RemoveHandler(EventPaddingChanged, value);
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Paint"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatAppearance), SRDescription(SR.ControlOnPaintDescr)]
        public event PaintEventHandler Paint {
            add {
                Events.AddHandler(EventPaint, value);
            }
            remove {
                Events.RemoveHandler(EventPaint, value);
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.QueryContinueDrag"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatDragDrop), SRDescription(SR.ControlOnQueryContinueDragDescr)]
        public event QueryContinueDragEventHandler QueryContinueDrag {
            add {
                Events.AddHandler(EventQueryContinueDrag, value);
            }
            remove {
                Events.RemoveHandler(EventQueryContinueDrag, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.QueryAccessibilityHelp"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatBehavior), SRDescription(SR.ControlOnQueryAccessibilityHelpDescr)]
        public event QueryAccessibilityHelpEventHandler QueryAccessibilityHelp {
            add {
                Events.AddHandler(EventQueryAccessibilityHelp, value);
            }
            remove {
                Events.RemoveHandler(EventQueryAccessibilityHelp, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.DoubleClick"]/*' />
        /// <devdoc>
        ///    <para>Occurs when the control is double clicked.</para>
        /// </devdoc>
        [SRCategory(SR.CatAction), SRDescription(SR.ControlOnDoubleClickDescr)]
        public event EventHandler DoubleClick {
            add {
                Events.AddHandler(EventDoubleClick, value);
            }
            remove {
                Events.RemoveHandler(EventDoubleClick, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Enter"]/*' />
        /// <devdoc>
        ///    <para>Occurs when the control is entered.</para>
        /// </devdoc>
        [SRCategory(SR.CatFocus), SRDescription(SR.ControlOnEnterDescr)]
        public event EventHandler Enter {
            add {
                Events.AddHandler(EventEnter, value);
            }
            remove {
                Events.RemoveHandler(EventEnter, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.GotFocus"]/*' />
        /// <devdoc>
        ///    <para>Occurs when the control receives focus.</para>
        /// </devdoc>
        [SRCategory(SR.CatFocus), SRDescription(SR.ControlOnGotFocusDescr), Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)]
        public event EventHandler GotFocus {
            add {
                Events.AddHandler(EventGotFocus, value);
            }
            remove {
                Events.RemoveHandler(EventGotFocus, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.KeyDown"]/*' />
        /// <devdoc>
        ///    <para>Occurs when a key is pressed down while the control has focus.</para>
        /// </devdoc>
        [SRCategory(SR.CatKey), SRDescription(SR.ControlOnKeyDownDescr)]
        public event KeyEventHandler KeyDown {
            add {
                Events.AddHandler(EventKeyDown, value);
            }
            remove {
                Events.RemoveHandler(EventKeyDown, value);
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.KeyPress"]/*' />
        /// <devdoc>
        ///    <para> Occurs when a key is pressed while the control has focus.</para>
        /// </devdoc>
        [SRCategory(SR.CatKey), SRDescription(SR.ControlOnKeyPressDescr)]
        public event KeyPressEventHandler KeyPress {
            add {
                Events.AddHandler(EventKeyPress, value);
            }
            remove {
                Events.RemoveHandler(EventKeyPress, value);
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.KeyUp"]/*' />
        /// <devdoc>
        ///    <para> Occurs when a key is released while the control has focus.</para>
        /// </devdoc>
        [SRCategory(SR.CatKey), SRDescription(SR.ControlOnKeyUpDescr)]
        public event KeyEventHandler KeyUp {
            add {
                Events.AddHandler(EventKeyUp, value);
            }
            remove {
                Events.RemoveHandler(EventKeyUp, value);
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Layout"]/*' />
        /// <devdoc>
        /// </devdoc>
        [SRCategory(SR.CatLayout), SRDescription(SR.ControlOnLayoutDescr)]
        public event LayoutEventHandler Layout {
            add {
                Events.AddHandler(EventLayout, value);
            }
            remove {
                Events.RemoveHandler(EventLayout, value);
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Leave"]/*' />
        /// <devdoc>
        ///    <para>Occurs when the control is left.</para>
        /// </devdoc>
        [SRCategory(SR.CatFocus), SRDescription(SR.ControlOnLeaveDescr)]
        public event EventHandler Leave {
            add {
                Events.AddHandler(EventLeave, value);
            }
            remove {
                Events.RemoveHandler(EventLeave, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.LostFocus"]/*' />
        /// <devdoc>
        ///    <para>Occurs when the control loses focus.</para>
        /// </devdoc>
        [SRCategory(SR.CatFocus), SRDescription(SR.ControlOnLostFocusDescr), Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)]
        public event EventHandler LostFocus {
            add {
                Events.AddHandler(EventLostFocus, value);
            }
            remove {
                Events.RemoveHandler(EventLostFocus, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.MouseClick"]/*' />
        /// <devdoc>
        ///    <para>Occurs when the control is mouse clicked.</para>
        /// </devdoc>
        [SRCategory(SR.CatAction), SRDescription(SR.ControlOnMouseClickDescr)]
        public event MouseEventHandler MouseClick {
            add {
                Events.AddHandler(EventMouseClick, value);
            }
            remove {
                Events.RemoveHandler(EventMouseClick, value);
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.MouseDoubleClick"]/*' />
        /// <devdoc>
        ///    <para>Occurs when the control is mouse double clicked.</para>
        /// </devdoc>
        [SRCategory(SR.CatAction), SRDescription(SR.ControlOnMouseDoubleClickDescr)]
        public event MouseEventHandler MouseDoubleClick {
            add {
                Events.AddHandler(EventMouseDoubleClick, value);
            }
            remove {
                Events.RemoveHandler(EventMouseDoubleClick, value);
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.MouseCaptureChanged"]/*' />
        /// <devdoc>
        ///    <para>Occurs when the control loses mouse Capture.</para>
        /// </devdoc>
        [SRCategory(SR.CatAction), SRDescription(SR.ControlOnMouseCaptureChangedDescr)]
        public event EventHandler MouseCaptureChanged {
            add {
                Events.AddHandler(EventMouseCaptureChanged, value);
            }
            remove {
                Events.RemoveHandler(EventMouseCaptureChanged, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.MouseDown"]/*' />
        /// <devdoc>
        ///    <para>Occurs when the mouse pointer is over the control and a mouse button is
        ///       pressed.</para>
        /// </devdoc>
        [SRCategory(SR.CatMouse), SRDescription(SR.ControlOnMouseDownDescr)]
        public event MouseEventHandler MouseDown {
            add {
                Events.AddHandler(EventMouseDown, value);
            }
            remove {
                Events.RemoveHandler(EventMouseDown, value);
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.MouseEnter"]/*' />
        /// <devdoc>
        ///    <para> Occurs when the mouse pointer enters the control.</para>
        /// </devdoc>
        [SRCategory(SR.CatMouse), SRDescription(SR.ControlOnMouseEnterDescr)]
        public event EventHandler MouseEnter {
            add {
                Events.AddHandler(EventMouseEnter, value);
            }
            remove {
                Events.RemoveHandler(EventMouseEnter, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.MouseLeave"]/*' />
        /// <devdoc>
        ///    <para> Occurs when the mouse pointer leaves the control.</para>
        /// </devdoc>
        [SRCategory(SR.CatMouse), SRDescription(SR.ControlOnMouseLeaveDescr)]
        public event EventHandler MouseLeave {
            add {
                Events.AddHandler(EventMouseLeave, value);
            }
            remove {
                Events.RemoveHandler(EventMouseLeave, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.DpiChangedBeforeParent"]/*' />
        /// <devdoc>
        ///    <para> Occurs when the DPI resolution of the screen this control is displayed on changes, 
        ///    either when the top level window is moved between monitors or when the OS settings are changed.
        ///    This event is raised before the top level parent window recieves WM_DPICHANGED message.
        ///    </para>
        /// </devdoc>
        [SRCategory(SR.CatLayout), SRDescription(SR.ControlOnDpiChangedBeforeParentDescr)]
        public event EventHandler DpiChangedBeforeParent {
            add {
                Events.AddHandler(EventDpiChangedBeforeParent, value);
            }
            remove {
                Events.RemoveHandler(EventDpiChangedBeforeParent, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.DpiChangedAfterParent"]/*' />
        /// <devdoc>
        ///    <para> Occurs when the DPI resolution of the screen this control is displayed on changes, 
        ///    either when the top level window is moved between monitors or when the OS settings are changed.
        ///    This message is received after the top levet parent window recieves WM_DPICHANGED message.
        ///    </para>
        /// </devdoc>
        [SRCategory(SR.CatLayout), SRDescription(SR.ControlOnDpiChangedAfterParentDescr)]
        public event EventHandler DpiChangedAfterParent {
            add {
                Events.AddHandler(EventDpiChangedAfterParent, value);
            }
            remove {
                Events.RemoveHandler(EventDpiChangedAfterParent, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.MouseHover"]/*' />
        /// <devdoc>
        ///    <para> Occurs when the mouse pointer hovers over the contro.</para>
        /// </devdoc>
        [SRCategory(SR.CatMouse), SRDescription(SR.ControlOnMouseHoverDescr)]
        public event EventHandler MouseHover {
            add {
                Events.AddHandler(EventMouseHover, value);
            }
            remove {
                Events.RemoveHandler(EventMouseHover, value);
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.MouseMove"]/*' />
        /// <devdoc>
        ///    <para> Occurs when the mouse pointer is moved over the control.</para>
        /// </devdoc>
        [SRCategory(SR.CatMouse), SRDescription(SR.ControlOnMouseMoveDescr)]
        public event MouseEventHandler MouseMove {
            add {
                Events.AddHandler(EventMouseMove, value);
            }
            remove {
                Events.RemoveHandler(EventMouseMove, value);
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.MouseUp"]/*' />
        /// <devdoc>
        ///    <para>Occurs when the mouse pointer is over the control and a mouse button is released.</para>
        /// </devdoc>
        [SRCategory(SR.CatMouse), SRDescription(SR.ControlOnMouseUpDescr)]
        public event MouseEventHandler MouseUp {
            add {
                Events.AddHandler(EventMouseUp, value);
            }
            remove {
                Events.RemoveHandler(EventMouseUp, value);
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.MouseWheel"]/*' />
        /// <devdoc>
        ///    <para> Occurs when the mouse wheel moves while the control has focus.</para>
        /// </devdoc>
        [SRCategory(SR.CatMouse), SRDescription(SR.ControlOnMouseWheelDescr), Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)]
        public event MouseEventHandler MouseWheel {
            add {
                Events.AddHandler(EventMouseWheel, value);
            }
            remove {
                Events.RemoveHandler(EventMouseWheel, value);
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Move"]/*' />
        /// <devdoc>
        ///    <para>Occurs when the control is moved.</para>
        /// </devdoc>
        [SRCategory(SR.CatLayout), SRDescription(SR.ControlOnMoveDescr)]
        public event EventHandler Move {
            add {
                Events.AddHandler(EventMove, value);
            }
            remove {
                Events.RemoveHandler(EventMove, value);
            }
        }
 
        /// <devdoc>
        ///    <para>Raised to preview a key down event</para>
        /// </devdoc>
        [SRCategory(SR.CatKey), SRDescription(SR.PreviewKeyDownDescr)]
        public event PreviewKeyDownEventHandler PreviewKeyDown {
            [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
            add {
                Events.AddHandler(EventPreviewKeyDown, value);
            }
            [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
            remove {
                Events.RemoveHandler(EventPreviewKeyDown, value);
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Resize"]/*' />
        /// <devdoc>
        ///    <para>Occurs when the control is resized.</para>
        /// </devdoc>
        [SRCategory(SR.CatLayout), SRDescription(SR.ControlOnResizeDescr),
         EditorBrowsable(EditorBrowsableState.Advanced)]
        public event EventHandler Resize {
            add {
                Events.AddHandler(EventResize, value);
            }
            remove {
                Events.RemoveHandler(EventResize, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.ChangeUICues"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatBehavior), SRDescription(SR.ControlOnChangeUICuesDescr)]
        public event UICuesEventHandler ChangeUICues {
            add {
                Events.AddHandler(EventChangeUICues, value);
            }
            remove {
                Events.RemoveHandler(EventChangeUICues, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.StyleChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatBehavior), SRDescription(SR.ControlOnStyleChangedDescr)]
        public event EventHandler StyleChanged {
            add {
                Events.AddHandler(EventStyleChanged, value);
            }
            remove {
                Events.RemoveHandler(EventStyleChanged, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.SystemColorsChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatBehavior), SRDescription(SR.ControlOnSystemColorsChangedDescr)]
        public event EventHandler SystemColorsChanged {
            add {
                Events.AddHandler(EventSystemColorsChanged, value);
            }
            remove {
                Events.RemoveHandler(EventSystemColorsChanged, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Validating"]/*' />
        /// <devdoc>
        ///    <para>Occurs when the control is validating.</para>
        /// </devdoc>
        [SRCategory(SR.CatFocus), SRDescription(SR.ControlOnValidatingDescr)]
        public event CancelEventHandler Validating {
            add {
                Events.AddHandler(EventValidating, value);
            }
            remove {
                Events.RemoveHandler(EventValidating, value);
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Validated"]/*' />
        /// <devdoc>
        ///    <para>Occurs when the control is done validating.</para>
        /// </devdoc>
        [SRCategory(SR.CatFocus), SRDescription(SR.ControlOnValidatedDescr)]
        public event EventHandler Validated {
            add {
                Events.AddHandler(EventValidated, value);
            }
            remove {
                Events.RemoveHandler(EventValidated, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.AccessibilityNotifyClients"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected internal void AccessibilityNotifyClients(AccessibleEvents accEvent, int childID) {
            AccessibilityNotifyClients(accEvent, NativeMethods.OBJID_CLIENT, childID);
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.AccessibilityNotifyClients1"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected void AccessibilityNotifyClients(AccessibleEvents accEvent, int objectID, int childID) {
            if (IsHandleCreated) {
                UnsafeNativeMethods.NotifyWinEvent((int)accEvent, new HandleRef(this, Handle), objectID, childID + 1);
            }
        }
 
        /// <devdoc>
        ///     Helper method for retrieving an ActiveX property.  We abstract these
        ///     to another method so we do not force JIT the ActiveX codebase.
        /// </devdoc>
        [ResourceExposure(ResourceScope.Process)]
        [ResourceConsumption(ResourceScope.Process)]
        private IntPtr ActiveXMergeRegion(IntPtr region) {
            return ActiveXInstance.MergeRegion(region);
        }
 
        /// <devdoc>
        ///     Helper method for retrieving an ActiveX property.  We abstract these
        ///     to another method so we do not force JIT the ActiveX codebase.
        /// </devdoc>
        private void ActiveXOnFocus(bool focus) {
            ActiveXInstance.OnFocus(focus);
        }
 
        /// <devdoc>
        ///     Helper method for retrieving an ActiveX property.  We abstract these
        ///     to another method so we do not force JIT the ActiveX codebase.
        /// </devdoc>
        private void ActiveXViewChanged() {
            ActiveXInstance.ViewChangedInternal();
        }
 
        #if ACTIVEX_SOURCING

        //
        // This has been cut from the product.
        //
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.ActiveXRegister"]/*' />
        /// <devdoc>
        ///     This is called by regasm to register a control as an ActiveX control.
        /// </devdoc>
        [ComRegisterFunction()]
        protected static void ActiveXRegister(Type type) {
 
            if (type == null) {
                throw new ArgumentNullException("type");
            }
 
            // If the user is not registering an AX control, then
            // bail now.
            //
            if (!typeof(Control).IsAssignableFrom(type)) {
                return;
            }
 
            // Add the flags that define us as a control to the rest of the
            // world.
            //
            RegistryKey clsidKey = Registry.ClassesRoot.OpenSubKey("CLSID", true).CreateSubKey("{" + type.GUID.ToString() + "}");
            RegistryKey key = clsidKey.CreateSubKey("Control");
            key.Close();
 
            key = clsidKey.CreateSubKey("Implemented Categories");
            RegistryKey subKey = key.CreateSubKey("{40FC6ED4-2438-11CF-A3DB-080036F12502}"); // CATID_Control
            subKey.Close();
            key.Close();
 
            // Calculate MiscStatus bits.  Note that this is a static version
            // of GetMiscStatus in ActiveXImpl below.  Keep them in sync!
            //
            int miscStatus = NativeMethods.OLEMISC_ACTIVATEWHENVISIBLE |
                             NativeMethods.OLEMISC_INSIDEOUT |
                             NativeMethods.OLEMISC_SETCLIENTSITEFIRST |
                             NativeMethods.OLEMISC_RECOMPOSEONRESIZE;
            if (typeof(IButtonControl).IsAssignableFrom(type)) {
                miscStatus |= NativeMethods.OLEMISC_ACTSLIKEBUTTON;
            }
 
            key = clsidKey.CreateSubKey("MiscStatus");
            key.SetValue("", miscStatus.ToString());
            key.Close();
 
            // Now add the typelib information.  Many containers don't
            // host Active X controls without a typelib in the registry
            // (visual basic won't even show it in the control dialog).
            //
            Guid typeLibGuid = Marshal.GetTypeLibGuidForAssembly(type.Assembly);
            Version assemblyVer = type.Assembly.GetName().Version;
 
            if (typeLibGuid != Guid.Empty) {
                key = clsidKey.CreateSubKey("TypeLib");
                key.SetValue("", "{" + typeLibGuid.ToString() + "}");
                key.Close();
                key = clsidKey.CreateSubKey("Version");
                key.SetValue("", assemblyVer.Major.ToString() + "." + assemblyVer.Minor.ToString());
                key.Close();
            }
 
            clsidKey.Close();
        }
        #endif
 
        /// <devdoc>
        ///     Helper method for retrieving an ActiveX property.  We abstract these
        ///     to another method so we do not force JIT the ActiveX codebase.
        /// </devdoc>
        private void ActiveXUpdateBounds(ref int x, ref int y, ref int width, ref int height, int flags) {
            ActiveXInstance.UpdateBounds(ref x, ref y, ref width, ref height, flags);
        }
 
        #if ACTIVEX_SOURCING

        //
        // This has been cut from the product.
        //
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.ActiveXUnregister"]/*' />
        /// <devdoc>
        ///     This is called by regasm to un-register a control as an ActiveX control.
        /// </devdoc>
        [ComUnregisterFunction()]
        protected static void ActiveXUnregister(Type type) {
 
            if (type == null) {
                throw new ArgumentNullException("type");
            }
 
            // If the user is not unregistering an AX control, then
            // bail now.
            //
            if (!typeof(Control).IsAssignableFrom(type)) {
                return;
            }
 
            RegistryKey clsidKey = null;
 
            // Unregistration should be very robust and unregister what it can.  We eat all exceptions here.
            //
            try {
                clsidKey = Registry.ClassesRoot.OpenSubKey("CLSID", true).CreateSubKey("{" + type.GUID.ToString() + "}");
 
                try {
                    clsidKey.DeleteSubKeyTree("Control");
                }
                catch {
                }
                try {
                    clsidKey.DeleteSubKeyTree("Implemented Categories");
                }
                catch {
                }
                try {
                    clsidKey.DeleteSubKeyTree("MiscStatus");
                }
                catch {
                }
                try {
                    clsidKey.DeleteSubKeyTree("TypeLib");
                }
                catch {
                }
            }
            finally {
                if (clsidKey != null) {
                    clsidKey.Close();
                }
            }
        }
        #endif
 
        /// <devdoc>
        ///     Assigns a new parent control. Sends out the appropriate property change
        ///     notifications for properties that are affected by the change of parent.
        /// </devdoc>
        internal virtual void AssignParent(Control value) {
 
            // Adopt the parent's required scaling bits
            if (value != null) {
                RequiredScalingEnabled = value.RequiredScalingEnabled;
            }
 
            if (CanAccessProperties) {
                // Store the old values for these properties
                //
                Font oldFont = Font;
                Color oldForeColor = ForeColor;
                Color oldBackColor = BackColor;
                RightToLeft oldRtl = RightToLeft;
                bool oldEnabled = Enabled;
                bool oldVisible = Visible;
 
                // Update the parent
                //
                parent = value;
                OnParentChanged(EventArgs.Empty);                
 
                if (GetAnyDisposingInHierarchy()) {
                    return;
                }                
 
                // Compare property values with new parent to old values
                //
                if (oldEnabled != Enabled) {
                    OnEnabledChanged(EventArgs.Empty);
                }
 
                // VSWhidbey 320131
                // When a control seems to be going from invisible -> visible,
                // yet its parent is being set to null and it's not top level, do not raise OnVisibleChanged.
                bool newVisible = Visible;
                
                if (oldVisible != newVisible && !(!oldVisible && newVisible && parent == null && !GetTopLevel())) {
                    OnVisibleChanged(EventArgs.Empty);
                }
                if (!oldFont.Equals(Font)) {
                    OnFontChanged(EventArgs.Empty);
                }
                if (!oldForeColor.Equals(ForeColor)) {
                    OnForeColorChanged(EventArgs.Empty);
                }
                if (!oldBackColor.Equals(BackColor)) {
                    OnBackColorChanged(EventArgs.Empty);
                }
                if (oldRtl != RightToLeft) {
                    OnRightToLeftChanged(EventArgs.Empty);
                }
                if (Properties.GetObject(PropBindingManager) == null && this.Created) {
                    // We do not want to call our parent's BindingContext property here.
                    // We have no idea if us or any of our children are using data binding,
                    // and invoking the property would just create the binding manager, which
                    // we don't need.  We just blindly notify that the binding manager has
                    // changed, and if anyone cares, they will do the comparison at that time.
                    //
                    OnBindingContextChanged(EventArgs.Empty);
                }
            }
            else {
                parent = value;
                OnParentChanged(EventArgs.Empty);
            }
 
            SetState(STATE_CHECKEDHOST, false);
            if (ParentInternal != null) ParentInternal.LayoutEngine.InitLayout(this, BoundsSpecified.All);
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.ParentChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ControlOnParentChangedDescr)]
        public event EventHandler ParentChanged {
            add {
                Events.AddHandler(EventParent, value);
            }
            remove {
                Events.RemoveHandler(EventParent, value);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.BeginInvoke"]/*' />
        /// <devdoc>
        ///     Executes the given delegate on the thread that owns this Control's
        ///     underlying window handle.  The delegate is called asynchronously and this
        ///     method returns immediately.  You may call this from any thread, even the
        ///     thread that owns the control's handle.  If the control's handle doesn't
        ///     exist yet, this will follow up the control's parent chain until it finds a
        ///     control or form that does have a window handle.  If no appropriate handle
        ///     can be found, BeginInvoke will throw an exception.  Exceptions within the
        ///     delegate method are considered untrapped and will be sent to the
        ///     application's untrapped exception handler.
        ///
        ///     There are five functions on a control that are safe to call from any
        ///     thread:  GetInvokeRequired, Invoke, BeginInvoke, EndInvoke and CreateGraphics.
        ///     For all other method calls, you should use one of the invoke methods to marshal
        ///     the call to the control's thread.
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        public IAsyncResult BeginInvoke(Delegate method) {
            return BeginInvoke(method, null);
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.BeginInvoke1"]/*' />
        /// <devdoc>
        ///     Executes the given delegate on the thread that owns this Control's
        ///     underlying window handle.  The delegate is called asynchronously and this
        ///     method returns immediately.  You may call this from any thread, even the
        ///     thread that owns the control's handle.  If the control's handle doesn't
        ///     exist yet, this will follow up the control's parent chain until it finds a
        ///     control or form that does have a window handle.  If no appropriate handle
        ///     can be found, BeginInvoke will throw an exception.  Exceptions within the
        ///     delegate method are considered untrapped and will be sent to the
        ///     application's untrapped exception handler.
        ///
        ///     There are five functions on a control that are safe to call from any
        ///     thread:  GetInvokeRequired, Invoke, BeginInvoke, EndInvoke and CreateGraphics.
        ///     For all other method calls, you should use one of the invoke methods to marshal
        ///     the call to the control's thread.
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]        
        [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
        public IAsyncResult BeginInvoke(Delegate method, params Object[] args) {
            using (new MultithreadSafeCallScope()) {
                Control marshaler = FindMarshalingControl();
                return(IAsyncResult)marshaler.MarshaledInvoke(this, method, args, false);
            }
        }
 
        internal void BeginUpdateInternal() {
            if (!IsHandleCreated) {
                return;
            }
            if (updateCount == 0) SendMessage(NativeMethods.WM_SETREDRAW, 0, 0);
            updateCount++;
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.BringToFront"]/*' />
        /// <devdoc>
        ///     Brings this control to the front of the zorder.
        /// </devdoc>
        public void BringToFront() {
            if (parent != null) {
                parent.Controls.SetChildIndex(this, 0);
            }
            else if (IsHandleCreated && GetTopLevel() && SafeNativeMethods.IsWindowEnabled(new HandleRef(window, Handle))) {
                SafeNativeMethods.SetWindowPos(new HandleRef(window, Handle), NativeMethods.HWND_TOP, 0, 0, 0, 0,
                                               NativeMethods.SWP_NOMOVE | NativeMethods.SWP_NOSIZE);
            }
        }
 
        /// <devdoc>
        ///     Specifies whether this control can process the mnemonic or not.  A condition to process a mnemonic is that
        ///     all controls in the parent chain can do it too, but since the semantics for this function can be overriden,
        ///     we need to call the method on the parent 'recursively' (not exactly since it is not necessarily the same method).
        /// </devdoc>
        internal virtual bool CanProcessMnemonic() {
#if DEBUG
            TraceCanProcessMnemonic();
#endif
            if( !this.Enabled || !this.Visible) {
                return false;
            }
 
            if( this.parent != null ){
                return this.parent.CanProcessMnemonic();
            }
 
            return true;
        }
 
        // Package scope to allow AxHost to override
        //
        internal virtual bool CanSelectCore() {
            if ((controlStyle & ControlStyles.Selectable) != ControlStyles.Selectable) {
                return false;
            }
 
            for (Control ctl = this; ctl != null; ctl = ctl.parent) {
                if (!ctl.Enabled || !ctl.Visible) {
                    return false;
                }
            }
 
            return true;
        }
 
        /// <devdoc>
        ///     Searches the parent/owner tree for bottom to find any instance
        ///     of toFind in the parent/owner tree.
        /// </devdoc>
        internal static void CheckParentingCycle(Control bottom, Control toFind) {
            Form lastOwner = null;
            Control lastParent = null;
 
            for (Control ctl = bottom; ctl != null; ctl = ctl.ParentInternal) {
                lastParent = ctl;
                if (ctl == toFind) {
                    throw new ArgumentException(SR.GetString(SR.CircularOwner));
                }
            }
 
            if (lastParent != null) {
                if (lastParent is Form) {
                    Form f = (Form)lastParent;
                    for (Form form = f; form != null; form = form.OwnerInternal) {
                        lastOwner = form;
                        if (form == toFind) {
                            throw new ArgumentException(SR.GetString(SR.CircularOwner));
                        }
                    }
                }
            }
 
            if (lastOwner != null) {
                if (lastOwner.ParentInternal != null) {
                    CheckParentingCycle(lastOwner.ParentInternal, toFind);
                }
            }
        }
        /// <devdoc>
        /// </devdoc>
        /// <internalonly/>
        private void ChildGotFocus(Control child) {
            if (IsActiveX) {
                ActiveXOnFocus(true);
            }
            if (parent != null) {
                parent.ChildGotFocus(child);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Contains"]/*' />
        /// <devdoc>
        ///    <para>Verifies if a control is a child of this control.</para>
        /// </devdoc>
        public bool Contains(Control ctl) {
            while (ctl != null) {
                ctl = ctl.ParentInternal;
                if (ctl == null) {
                    return false;
                }
                if (ctl == this) {
                    return true;
                }
            }
            return false;
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.CreateAccessibilityInstance"]/*' />
        /// <devdoc>
        ///     constructs the new instance of the accessibility object for this control. Subclasses
        ///     should not call base.CreateAccessibilityObject.
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual AccessibleObject CreateAccessibilityInstance() {
            return new ControlAccessibleObject(this);
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.CreateControlsInstance"]/*' />
        /// <devdoc>
        ///     Constructs the new instance of the Controls collection objects. Subclasses
        ///     should not call base.CreateControlsInstance.
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual ControlCollection CreateControlsInstance() {
            return new System.Windows.Forms.Control.ControlCollection(this);
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.CreateGraphics"]/*' />
        /// <devdoc>
        ///     Creates a Graphics for this control. The control's brush, font, foreground
        ///     color and background color become the default values for the Graphics.
        ///     The returned Graphics must be disposed through a call to its dispose()
        ///     method when it is no longer needed.  The Graphics Object is only valid for
        ///     the duration of the current window's message.
        /// </devdoc>
        [ResourceExposure(ResourceScope.Process)]
        [ResourceConsumption(ResourceScope.Process)]
        public System.Drawing.Graphics CreateGraphics() {
            using (new MultithreadSafeCallScope())
            {
                Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "CreateGraphicsForControl Demanded");
                IntSecurity.CreateGraphicsForControl.Demand();
                return CreateGraphicsInternal();
            }
        }
 
        
        // SECURITY WARNING: This property bypasses a security demand. Use with caution!
        [ResourceExposure(ResourceScope.Process)]
        [ResourceConsumption(ResourceScope.Process)]
        internal System.Drawing.Graphics CreateGraphicsInternal() {
            return Graphics.FromHwndInternal(this.Handle);
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.CreateHandle"]/*' />
        /// <devdoc>
        ///     Creates a handle for this control. This method is called by the .NET Framework, this should
        ///     not be called. Inheriting classes should always call base.createHandle when
        ///     overriding this method.
        /// </devdoc>
        [
        EditorBrowsable(EditorBrowsableState.Advanced),
        UIPermission(SecurityAction.InheritanceDemand, Window=UIPermissionWindow.AllWindows)
        ]
        protected virtual void CreateHandle() {
            IntPtr userCookie = IntPtr.Zero;
 
            if (GetState(STATE_DISPOSED)) {
                throw new System.ObjectDisposedException(GetType().Name);
            }
 
            if (GetState(STATE_CREATINGHANDLE)) {
                return;
            }
 
            Rectangle originalBounds;
 
            try {
                SetState(STATE_CREATINGHANDLE, true);
 
                originalBounds = this.Bounds;
 
                if (Application.UseVisualStyles) {
                    // Activate theming scope to get theming for controls at design time and when hosted in browser.
                    // NOTE: If a theming context is already active, this call is very fast, so shouldn't be a perf issue.
                    userCookie = UnsafeNativeMethods.ThemingScope.Activate();
                }
 
                CreateParams cp = CreateParams;
                SetState(STATE_MIRRORED, (cp.ExStyle & NativeMethods.WS_EX_LAYOUTRTL) != 0);
 
                // Adjust for scrolling of parent...
                //
                if (parent != null) {
                    Rectangle parentClient = parent.ClientRectangle;
 
                    if (!parentClient.IsEmpty) {
                        if (cp.X != NativeMethods.CW_USEDEFAULT) {
                            cp.X -= parentClient.X;
                        }
                        if (cp.Y != NativeMethods.CW_USEDEFAULT) {
                            cp.Y -= parentClient.Y;
                        }
                    }
                }
 
                // And if we are WS_CHILD, ensure we have a parent handle.
                //
                if (cp.Parent == IntPtr.Zero && (cp.Style & NativeMethods.WS_CHILD) != 0) {
                    Debug.Assert((cp.ExStyle & NativeMethods.WS_EX_MDICHILD) == 0, "Can't put MDI child forms on the parking form");
                    Application.ParkHandle(cp, this.DpiAwarenessContext);
                }
 
                window.CreateHandle(cp);
 
                UpdateReflectParent(true);
 
            }
            finally {
                SetState(STATE_CREATINGHANDLE, false);
                UnsafeNativeMethods.ThemingScope.Deactivate(userCookie);
            }
 
            // VSWhidbey #121382 - For certain controls (e.g., ComboBox) CreateWindowEx
            // may cause the control to resize.  WM_SETWINDOWPOSCHANGED takes care of
            // the control being resized, but our layout container may need a refresh as well.
            if (this.Bounds != originalBounds) {
                LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.Bounds);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.CreateControl"]/*' />
        /// <devdoc>
        ///     Forces the creation of the control. This includes the creation of the handle,
        ///     and any child controls.
        /// </devdoc>
        public void CreateControl() {
            bool controlIsAlreadyCreated = this.Created;
            CreateControl(false);
 
            if (Properties.GetObject(PropBindingManager) == null && ParentInternal != null && !controlIsAlreadyCreated) {
                // We do not want to call our parent's BindingContext property here.
                // We have no idea if us or any of our children are using data binding,
                // and invoking the property would just create the binding manager, which
                // we don't need.  We just blindly notify that the binding manager has
                // changed, and if anyone cares, they will do the comparison at that time.
                OnBindingContextChanged(EventArgs.Empty);
            }
        }
 
        /// <devdoc>
        ///     Forces the creation of the control. This includes the creation of the handle,
        ///     and any child controls.
        /// <param name='fIgnoreVisible'>
        ///     Determines whether we should create the handle after checking the Visible
        ///     property of the control or not.
        /// </param>
        /// </devdoc>
        internal void CreateControl(bool fIgnoreVisible) {
            bool ready = (state & STATE_CREATED) == 0;
 
            // PERF: Only "create" the control if it is
            //     : visible. This has the effect of delayed handle creation of
            //     : hidden controls.
            //
            ready = ready && Visible;
 
            if (ready || fIgnoreVisible) {
                state |= STATE_CREATED;
                bool createdOK = false;
                try {
                    if (!IsHandleCreated) CreateHandle();
 
                    // 58041 - must snapshot this array because
                    // z-order updates from Windows may rearrange it!
                    //
                    ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection);
 
                    if (controlsCollection != null) {
                        Control[] controlSnapshot = new Control[controlsCollection.Count];
                        controlsCollection.CopyTo(controlSnapshot, 0);
 
                        foreach(Control ctl in controlSnapshot) {
                            if (ctl.IsHandleCreated) {
                                ctl.SetParentHandle(Handle);
                            }
                            ctl.CreateControl(fIgnoreVisible);
                        }
                    }
 
                    createdOK = true;
                }
                finally {
                    if (!createdOK)
                        state &= (~STATE_CREATED);
                }
                OnCreateControl();
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.DefWndProc"]/*' />
        /// <devdoc>
        ///     Sends the message to the default window proc.
        /// </devdoc>
        /* Primarily here for Form to override */
        [
            SecurityPermission(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode),
            SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode),
            EditorBrowsable(EditorBrowsableState.Advanced)
        ]
        protected virtual void DefWndProc(ref Message m) {
            window.DefWndProc(ref m);
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.DestroyHandle"]/*' />
        /// <devdoc>
        ///     Destroys the handle associated with this control. Inheriting classes should
        ///     always call base.destroyHandle.
        /// </devdoc>
        [
            SecurityPermission(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode),
            UIPermission(SecurityAction.LinkDemand, Window=UIPermissionWindow.AllWindows),
            EditorBrowsable(EditorBrowsableState.Advanced)
        ]
        protected virtual void DestroyHandle() {
 
            if (RecreatingHandle) {
                if (threadCallbackList != null) {
                    // See if we have a thread marshaling request pending.  If so, we will need to
                    // re-post it after recreating the handle.
                    //
                    lock (threadCallbackList) {
                        if (threadCallbackMessage != 0) {
                            NativeMethods.MSG msg = new NativeMethods.MSG();
                            if (UnsafeNativeMethods.PeekMessage(ref msg, new HandleRef(this, Handle), threadCallbackMessage,
                                                          threadCallbackMessage, NativeMethods.PM_NOREMOVE)) {
 
                                SetState(STATE_THREADMARSHALLPENDING, true);
                            }
                        }
                    }
                }
            }
 
            // If we're not recreating the handle, then any items in the thread callback list will
            // be orphaned.  An orphaned item is bad, because it will cause the thread to never
            // wake up.  So, we put exceptions into all these items and wake up all threads.
            // If we are recreating the handle, then we're fine because recreation will re-post
            // the thread callback message to the new handle for us.
            //
            if (!RecreatingHandle) {                
                if (threadCallbackList != null) {
                    lock (threadCallbackList) {
                        Exception ex = new System.ObjectDisposedException(GetType().Name);
 
                        while (threadCallbackList.Count > 0) {
                            ThreadMethodEntry entry = (ThreadMethodEntry)threadCallbackList.Dequeue();
                            entry.exception = ex;
                            entry.Complete();
                        }
                    }
                }
            }
 
            if (0 != (NativeMethods.WS_EX_MDICHILD & (int)(long)UnsafeNativeMethods.GetWindowLong(new HandleRef(window, InternalHandle), NativeMethods.GWL_EXSTYLE))) {
                UnsafeNativeMethods.DefMDIChildProc(InternalHandle, NativeMethods.WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
            }
            else {
                window.DestroyHandle();
            }
 
            trackMouseEvent = null;
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Dispose"]/*' />
        /// <devdoc>
        ///    <para>Disposes of the resources (other than memory) used by the
        ///    <see cref='System.Windows.Forms.Control'/>
        ///    .</para>
        /// </devdoc>
        protected override void Dispose(bool disposing) {
            if (GetState(STATE_OWNCTLBRUSH)) {
                object backBrush = Properties.GetObject(PropBackBrush);
                if (backBrush != null) {
                    IntPtr p = (IntPtr)backBrush;
                    if (p != IntPtr.Zero) {
                        SafeNativeMethods.DeleteObject(new HandleRef(this, p));
                    }
                    Properties.SetObject(PropBackBrush, null);
                }
            }
 
            //set reflectparent = null regardless of whether we are in the finalizer thread or not.
            UpdateReflectParent(false);
            if (disposing) {
                if (GetState(STATE_DISPOSING)) {
                    return;
                }
 
                if (GetState(STATE_CREATINGHANDLE)) {
                    throw new InvalidOperationException(SR.GetString(SR.ClosingWhileCreatingHandle, "Dispose"));
                    // I imagine most subclasses will get themselves in a half disposed state
                    // if this exception is thrown, but things will be equally broken if we ignore this error,
                    // and this way at least the user knows what they did wrong.
                }
 
                SetState(STATE_DISPOSING, true);
                this.SuspendLayout();
                try {
                    DisposeAxControls();
 
                    ContextMenu contextMenu = (ContextMenu)Properties.GetObject(PropContextMenu);
                    if (contextMenu != null) {
                        contextMenu.Disposed -= new EventHandler(DetachContextMenu);
                    }
 
                    ResetBindings();
 
                    if (IsHandleCreated) DestroyHandle();
 
                    if (parent != null) {
                        parent.Controls.Remove(this);
                    }
 
                    ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection);
 
                    if (controlsCollection != null) {
 
                        // PERFNOTE: This is more efficient than using Foreach.  Foreach
                        // forces the creation of an array subset enum each time we
                        // enumerate
                        for(int i = 0; i < controlsCollection.Count; i++) {
                            Control ctl = controlsCollection[i];
                            ctl.parent = null;
                            ctl.Dispose();
                        }
                        Properties.SetObject(PropControlsCollection, null);
                    }
 
                    base.Dispose(disposing);
                }
                finally {
                    this.ResumeLayout(false);
                    SetState(STATE_DISPOSING, false);
                    SetState(STATE_DISPOSED, true);
                }
            }
            else {
 
#if FINALIZATION_WATCH
                if (!GetState(STATE_DISPOSED)) {
                    Debug.Fail("Control of type '" + GetType().FullName +"' is being finalized that wasn't disposed\n" + allocationSite);
                }
#endif
                // This same post is done in NativeWindow's finalize method, so if you change
                // it, change it there too.
                //
                if (window != null) {
                    window.ForceExitMessageLoop();
                }
                base.Dispose(disposing);
            }
        }
 
        // Package scope to allow AxHost to override.
        //
        internal virtual void DisposeAxControls() {
            ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection);
 
            if (controlsCollection != null) {
                // PERFNOTE: This is more efficient than using Foreach.  Foreach
                // forces the creation of an array subset enum each time we
                // enumerate
                for(int i = 0; i < controlsCollection.Count; i++) {
                    controlsCollection[i].DisposeAxControls();
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.DoDragDrop"]/*' />
        /// <devdoc>
        ///     Begins a drag operation. The allowedEffects determine which
        ///     drag operations can occur. If the drag operation needs to interop
        ///     with applications in another process, data should either be
        ///     a base managed class (String, Bitmap, or Metafile) or some Object
        ///     that implements System.Runtime.Serialization.ISerializable. data can also be any Object that
        ///     implements System.Windows.Forms.IDataObject.
        /// </devdoc>
        [UIPermission(SecurityAction.Demand, Clipboard=UIPermissionClipboard.OwnClipboard)]
        public DragDropEffects DoDragDrop(Object data, DragDropEffects allowedEffects) {            
            int[] finalEffect = new int[] {(int)DragDropEffects.None};
            UnsafeNativeMethods.IOleDropSource dropSource = new DropSource( this );
            IComDataObject dataObject = null;
 
            if (data is IComDataObject) {
                dataObject = (IComDataObject)data;
            }
            else {
 
                DataObject iwdata = null;
                if (data is IDataObject) {
                    iwdata = new DataObject((IDataObject)data);
                }
                else {
                    iwdata = new DataObject();
                    iwdata.SetData(data);
                }
                dataObject = (IComDataObject)iwdata;
            }
 
            try {
                SafeNativeMethods.DoDragDrop(dataObject, dropSource, (int)allowedEffects, finalEffect);
            }
            catch (Exception e) {
                if (ClientUtils.IsSecurityOrCriticalException(e)) {
                    throw;
                }
            }
 
            return(DragDropEffects)finalEffect[0];
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.DrawToBitmap"]/*' />
        /// <devdoc>
        //      Trinity are currently calling IViewObject::Draw in order to render controls on Word & Excel
        //      before they are in place active. However this method is private and they need a public way to do this.
        //      This means that we will need to add a public method to control that supports rendering to a Bitmap:
        //      public virtual void DrawToBitmap(Bitmap bmp, RectangleF targetBounds)
        //      where target bounds is the bounds within which the control should render.
        /// </devdoc>
        [
            SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly"),
            SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters"),          // Using Bitmap instead of Image intentionally
            SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters"), // targetBounds is the name of the param passed in.
                                                                                                         // So we don't have to localize it.
            UIPermission(SecurityAction.Demand, Window=UIPermissionWindow.AllWindows)
        ]
        public void DrawToBitmap(Bitmap bitmap, Rectangle targetBounds) {
 
            if (bitmap == null) {
                throw new ArgumentNullException("bitmap");
            }
 
            if (targetBounds.Width <= 0 || targetBounds.Height <= 0
                || targetBounds.X < 0 || targetBounds.Y < 0) {
                throw new ArgumentException("targetBounds");
            }
 
            if (!IsHandleCreated) {
                CreateHandle();
            }
 
 
            int width = Math.Min(this.Width, targetBounds.Width);
            int height = Math.Min(this.Height, targetBounds.Height);
 
            using (Bitmap image = new Bitmap(width, height, bitmap.PixelFormat)) {
                using (Graphics g = Graphics.FromImage(image)) {
                    IntPtr hDc = g.GetHdc();
                    //send the actual wm_print message
                    UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.WM_PRINT, (IntPtr)hDc,
                        (IntPtr)(NativeMethods.PRF_CHILDREN | NativeMethods.PRF_CLIENT | NativeMethods.PRF_ERASEBKGND | NativeMethods.PRF_NONCLIENT));
 
                    //now BLT the result to the destination bitmap.
                    using (Graphics destGraphics = Graphics.FromImage(bitmap)) {
                        IntPtr desthDC = destGraphics.GetHdc();
                        SafeNativeMethods.BitBlt(new HandleRef(destGraphics, desthDC), targetBounds.X, targetBounds.Y, width, height,
                                                 new HandleRef(g, hDc), 0, 0, 0xcc0020);
                        destGraphics.ReleaseHdcInternal(desthDC);
                    }
 
                    g.ReleaseHdcInternal(hDc);
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.EndInvoke"]/*' />
        /// <devdoc>
        ///     Retrieves the return value of the asynchronous operation
        ///     represented by the IAsyncResult interface passed. If the
        ///     async operation has not been completed, this function will
        ///     block until the result is available.
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        public Object EndInvoke(IAsyncResult asyncResult) {
            using (new MultithreadSafeCallScope())
            {
                if (asyncResult == null) {
                    throw new ArgumentNullException("asyncResult");
                }
 
                ThreadMethodEntry entry = asyncResult as ThreadMethodEntry;
                if (entry == null) {
                    throw new ArgumentException(SR.GetString(SR.ControlBadAsyncResult),"asyncResult");
                }
                Debug.Assert(this == entry.caller, "Called BeginInvoke on one control, and the corresponding EndInvoke on a different control");
 
                if (!asyncResult.IsCompleted) {
                    int pid; // ignored
                    Control marshaler = FindMarshalingControl();
                    if (SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(marshaler, marshaler.Handle), out pid) == SafeNativeMethods.GetCurrentThreadId()) {
                        marshaler.InvokeMarshaledCallbacks();
                    }
                    else {
                        marshaler = entry.marshaler;
                        marshaler.WaitForWaitHandle(asyncResult.AsyncWaitHandle);
                    }
                }
 
                Debug.Assert(asyncResult.IsCompleted, "Why isn't this asyncResult done yet?");
                if (entry.exception != null) {
                    throw entry.exception;
                }
                return entry.retVal;
            }
        }
 
        internal bool EndUpdateInternal() {
            return EndUpdateInternal(true);
        }
 
        internal bool EndUpdateInternal(bool invalidate) {
            if (updateCount > 0) {
                Debug.Assert(IsHandleCreated, "Handle should be created by now");
                updateCount--;
                if (updateCount == 0) {
                    SendMessage(NativeMethods.WM_SETREDRAW, -1, 0);
                    if (invalidate) {
                        Invalidate();
                    }
 
                }
                return true;
            }
            else {
                return false;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.FindForm"]/*' />
        /// <devdoc>
        ///     Retrieves the form that this control is on. The control's parent
        ///     may not be the same as the form.
        /// </devdoc>
        [UIPermission(SecurityAction.Demand, Window=UIPermissionWindow.AllWindows)]
        public Form FindForm() {
            return FindFormInternal();
        }
 
        // SECURITY WARNING: This method bypasses a security demand. Use with caution!
        internal Form FindFormInternal() {
            Control cur = this;
            while (cur != null && !(cur is Form) ) {
                cur = cur.ParentInternal;
            }
            return (Form)cur;
        }
 
        /// <devdoc>
        ///     Attempts to find a control Object that we can use to marshal
        ///     calls.  We must marshal calls to a control with a window
        ///     handle, so we traverse up the parent chain until we find one.
        ///     Failing that, we just return ouselves.
        /// </devdoc>
        /// <internalonly/>
        private Control FindMarshalingControl() {
            // 
            lock(this) {
                Control c = this;
 
                while (c != null && !c.IsHandleCreated) {
                    Control p = c.ParentInternal;
                    c = p;
                }
 
                if (c == null) {
                    // No control with a created handle.  We
                    // just use our own control.  MarshaledInvoke
                    // will throw an exception because there
                    // is no handle.
                    //
                    c = this;
                }
                else {
                    Debug.Assert(c.IsHandleCreated, "FindMarshalingControl chose a bad control.");
                }
 
                return(Control)c;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.GetTopLevel"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected bool GetTopLevel() {
            return(state & STATE_TOPLEVEL) != 0;
        }
 
        /// <devdoc>
        ///     Used by AxHost to fire the CreateHandle event.
        /// </devdoc>
        /// <internalonly/>
        internal void RaiseCreateHandleEvent(EventArgs e) {
            EventHandler handler = (EventHandler)Events[EventHandleCreated];
            if (handler != null) handler(this, e);
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.RaiseKeyEvent"]/*' />
        /// <devdoc>
        ///     Raises the event associated with key with the event data of
        ///     e and a sender of this control.
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected void RaiseKeyEvent(object key, KeyEventArgs e) {
            KeyEventHandler handler = (KeyEventHandler)Events[key];
            if (handler != null) handler(this, e);
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.RaiseMouseEvent"]/*' />
        /// <devdoc>
        ///     Raises the event associated with key with the event data of
        ///     e and a sender of this control.
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected void RaiseMouseEvent(object key, MouseEventArgs e) {
            MouseEventHandler handler = (MouseEventHandler)Events[key];
            if (handler != null) handler(this, e);
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Focus"]/*' />
        /// <devdoc>
        ///    <para> Sets focus to the control.</para>
        ///    <para>Attempts to set focus to this control.</para>
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        public bool Focus() {
            Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "Control::Focus - " + this.Name);
            Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "ModifyFocus Demanded");
            IntSecurity.ModifyFocus.Demand();
 
            //here, we call our internal method (which form overrides)
            //see comments in FocusInternal
            //
            return FocusInternal();
        }
 
        /// <devdoc>
        ///    Internal method for setting focus to the control.
        ///    Form overrides this method - because MDI child forms
        ///    need to be focused by calling the MDIACTIVATE message.
        /// </devdoc>
        // SECURITY WARNING: This method bypasses a security demand. Use with caution!
        internal virtual bool FocusInternal() {
            Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "Control::FocusInternal - " + this.Name);
            if (CanFocus){
                UnsafeNativeMethods.SetFocus(new HandleRef(this, Handle));
            }
            if (Focused && this.ParentInternal != null) {
                IContainerControl c = this.ParentInternal.GetContainerControlInternal();
 
                if (c != null) {
                    if (c is ContainerControl) {
                        ((ContainerControl)c).SetActiveControlInternal(this);
                    }
                    else {
                        c.ActiveControl = this;
                    }
                }
            }
 
 
            return Focused;
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.FromChildHandle"]/*' />
        /// <devdoc>
        ///     Returns the control that is currently associated with handle.
        ///     This method will search up the HWND parent chain until it finds some
        ///     handle that is associated with with a control. This method is more
        ///     robust that fromHandle because it will correctly return controls
        ///     that own more than one handle.
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        public static Control FromChildHandle(IntPtr handle) {
            Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "ControlFromHandleOrLocation Demanded");
            IntSecurity.ControlFromHandleOrLocation.Demand();
            return FromChildHandleInternal(handle);
        }
 
        // SECURITY WARNING: This method bypasses a security demand. Use with caution!
        internal static Control FromChildHandleInternal(IntPtr handle) {
            while (handle != IntPtr.Zero) {
                Control ctl = FromHandleInternal(handle);
                if (ctl != null) return ctl;
                handle = UnsafeNativeMethods.GetAncestor(new HandleRef(null, handle), NativeMethods.GA_PARENT);
            }
            return null;
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.FromHandle"]/*' />
        /// <devdoc>
        ///     Returns the control that is currently associated with handle.
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        public static Control FromHandle(IntPtr handle) {
            Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "ControlFromHandleOrLocation Demanded");
            IntSecurity.ControlFromHandleOrLocation.Demand();
            return FromHandleInternal(handle);
        }
 
        // SECURITY WARNING: This method bypasses a security demand. Use with caution!
        internal static Control FromHandleInternal(IntPtr handle) {
            NativeWindow w = NativeWindow.FromHandle(handle);
            while (w != null && !(w is ControlNativeWindow)) {
                w = w.PreviousWindow;
            }
 
            if (w is ControlNativeWindow) {
                return((ControlNativeWindow)w).GetControl();
            }
            return null;
        }
 
        // GetPreferredSize and SetBoundsCore call this method to allow controls to self impose
        // constraints on their size.
        internal Size ApplySizeConstraints(int width, int height) {
            return ApplyBoundsConstraints(0,0,width, height).Size;
        }
 
 
        // GetPreferredSize and SetBoundsCore call this method to allow controls to self impose
        // constraints on their size.
        internal Size ApplySizeConstraints(Size proposedSize) {
            return ApplyBoundsConstraints(0,0,proposedSize.Width,proposedSize.Height).Size;
        }
 
        internal virtual Rectangle ApplyBoundsConstraints(int suggestedX, int suggestedY, int proposedWidth, int proposedHeight) {
 
            // COMPAT: 529991 - in Everett we would allow you to set negative values in pre-handle mode
            // in Whidbey, if you've set Min/Max size we will constrain you to 0,0.  Everett apps didnt 
            // have min/max size on control, which is why this works.
            if (MaximumSize != Size.Empty || MinimumSize != Size.Empty) {
                Size maximumSize = LayoutUtils.ConvertZeroToUnbounded(MaximumSize);
                Rectangle newBounds = new Rectangle(suggestedX, suggestedY, 0,0);
      
                // Clip the size to maximum and inflate it to minimum as necessary.
                newBounds.Size = LayoutUtils.IntersectSizes(new Size(proposedWidth,proposedHeight), maximumSize);
                newBounds.Size = LayoutUtils.UnionSizes(newBounds.Size, MinimumSize);
      
                return newBounds;
            }
 
            return new Rectangle(suggestedX, suggestedY, proposedWidth, proposedHeight);
        }
 
        
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.GetChildAtPoint"]/*' />
        /// <devdoc>
        ///     Retrieves the child control that is located at the specified client
        ///     coordinates.
        /// </devdoc>
        public Control GetChildAtPoint(Point pt, GetChildAtPointSkip skipValue) {
            int value = (int)skipValue;
            // Since this is a Flags Enumeration... the only way to validate skipValue is by checking if its within the range.
            if(value < 0 || value > 7)
            {
                throw new InvalidEnumArgumentException("skipValue", value, typeof(GetChildAtPointSkip));
            }
 
            IntPtr hwnd = UnsafeNativeMethods.ChildWindowFromPointEx(new HandleRef(null, Handle), pt.X, pt.Y, value);
 
            // Security Reviewed
            // While doing a security review it was noticed that GetChildAtPoint
            // does work to ensure that you can only gain access to children of your own control,
            // but the methods it uses to determine the children demand all window permission first,
            // negating the extra check.
            // It is OK to return child windows for children within your own control for semitrust.
 
            // Hence  calling the Internal methods to ByPass the Security Demand...
            // for IntSecurity.ControlFromHandleOrLocation == ALLWindows.
 
            Control ctl = FromChildHandleInternal(hwnd);
            if (ctl != null && !IsDescendant(ctl)) {
                Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "ControlFromHandleOrLocation Demanded");
                IntSecurity.ControlFromHandleOrLocation.Demand();
            }
 
            return(ctl == this) ? null : ctl;
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.GetChildAtPoint"]/*' />
        /// <devdoc>
        ///     Retrieves the child control that is located at the specified client
        ///     coordinates.
        /// </devdoc>
        public Control GetChildAtPoint(Point pt) {
            return GetChildAtPoint(pt, GetChildAtPointSkip.None);
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.GetContainerControl"]/*' />
        /// <devdoc>
        ///     Returns the closest ContainerControl in the control's chain of
        ///     parent controls and forms.
        /// </devdoc>
        public IContainerControl GetContainerControl() {
            Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "GetParent Demanded");
            IntSecurity.GetParent.Demand();
            return GetContainerControlInternal();
        }
 
        private static bool IsFocusManagingContainerControl(Control ctl) {
            return ((ctl.controlStyle & ControlStyles.ContainerControl) == ControlStyles.ContainerControl && ctl is IContainerControl);
        }
 
    /// <devdoc>
        ///     This new Internal method checks the updateCount to signify that the control is within the "BeginUpdate" and "EndUpdate" cycle.
        ///     Check out Vs whidbey : 310110 : for usage of this. The Treeview tries to ForceUpdate the scrollbars by calling "WM_SETREDRAW"
        ///     even if the control in "Begin - End" update cycle. Using thie Function we can guard against repetitively redrawing the control.
        /// </devdoc>
        internal bool IsUpdating()
        {
            return (updateCount > 0);
        }
 
        // SECURITY WARNING: This method bypasses a security demand. Use with caution!
        internal IContainerControl GetContainerControlInternal() {
            Control c = this;
            
            // VsWhidbey 434959 : Refer to IsContainerControl property for more details.            
            if (c != null && IsContainerControl) 
            {
                c = c.ParentInternal;
            }
            while (c != null && (!IsFocusManagingContainerControl(c))) {
                c = c.ParentInternal;
            }
            return (IContainerControl)c;
        }
 
        // Essentially an Hfont; see inner class for details.
        private static FontHandleWrapper GetDefaultFontHandleWrapper() {
            if (defaultFontHandleWrapper == null) {
                defaultFontHandleWrapper = new FontHandleWrapper(DefaultFont);
            }
 
            return defaultFontHandleWrapper;
        }
 
        internal IntPtr GetHRgn(Region region) {
            Graphics graphics = CreateGraphicsInternal();
            IntPtr handle = region.GetHrgn(graphics);
            System.Internal.HandleCollector.Add(handle, NativeMethods.CommonHandles.GDI);
            graphics.Dispose();
            return handle;
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.GetScaledBounds"]/*' />
        /// <devdoc>
        ///     This is a helper method that is called by ScaleControl to retrieve the bounds
        ///     that the control should be scaled by.  You may override this method if you
        ///     wish to reuse ScaleControl's scaling logic but you need to supply your own
        ///     bounds.  The default implementation returns scaled bounds that take into
        ///     account the BoundsSpecified, whether the control is top level, and whether
        ///     the control is fixed width or auto size, and any adornments the control may have.
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual Rectangle GetScaledBounds(Rectangle bounds, SizeF factor, BoundsSpecified specified) {
 
            // We should not include the window adornments in our calculation,
            // because windows scales them for us.
            NativeMethods.RECT adornments = new NativeMethods.RECT(0, 0, 0, 0);
            CreateParams cp = CreateParams;
            AdjustWindowRectEx(ref adornments, cp.Style, HasMenu, cp.ExStyle);
 
            float dx = factor.Width;
            float dy = factor.Height;
 
            int sx = bounds.X;
            int sy = bounds.Y;
 
            // Don't reposition top level controls.  Also, if we're in
            // design mode, don't reposition the root component.
            bool scaleLoc = !GetState(STATE_TOPLEVEL);
            if (scaleLoc) {
                ISite site = Site;
                if (site != null && site.DesignMode) {
                    IDesignerHost host = site.GetService(typeof(IDesignerHost)) as IDesignerHost;
                    if (host != null && host.RootComponent == this) {
                        scaleLoc = false;
                    }
                }
            }
 
            if (scaleLoc) {
                if ((specified & BoundsSpecified.X) != 0) {
                    sx = (int)Math.Round(bounds.X * dx);
                }
 
                if ((specified & BoundsSpecified.Y) != 0) {
                    sy = (int)Math.Round(bounds.Y * dy);
                }
            }
 
            int sw = bounds.Width;
            int sh = bounds.Height;
 
            // Do this even for auto sized controls.  They'll "snap back", but it is important to size them in case
            // they are anchored.
            if ((controlStyle & ControlStyles.FixedWidth) != ControlStyles.FixedWidth && (specified & BoundsSpecified.Width) != 0) {
                int adornmentWidth = (adornments.right - adornments.left);
                int localWidth = bounds.Width - adornmentWidth;
                sw = (int)Math.Round(localWidth * dx) + adornmentWidth;
            }
            if ((controlStyle & ControlStyles.FixedHeight) != ControlStyles.FixedHeight && (specified & BoundsSpecified.Height) != 0) {
                int adornmentHeight = (adornments.bottom - adornments.top);
                int localHeight = bounds.Height - adornmentHeight;
                sh = (int)Math.Round(localHeight * dy) + adornmentHeight;
            }
 
            return new Rectangle(sx, sy, sw, sh);
        }
 
        private MouseButtons GetXButton(int wparam) {
            switch (wparam) {
            case NativeMethods.XBUTTON1:
                return MouseButtons.XButton1;
            case NativeMethods.XBUTTON2:
                return MouseButtons.XButton2;
            }
            Debug.Fail("Unknown XButton: " + wparam);
            return MouseButtons.None;
        }
 
        internal virtual bool GetVisibleCore() {
            // We are only visible if our parent is visible
            if (!GetState(STATE_VISIBLE))
                return false;
            else if (ParentInternal == null)
                return true;
            else
                return ParentInternal.GetVisibleCore();
        }
 
        internal bool GetAnyDisposingInHierarchy() {
            Control up = this;
            bool isDisposing = false;
            while (up != null) {
                if (up.Disposing) {
                    isDisposing = true;
                    break;
                }
                up = up.parent;
            }
            return isDisposing;
        }
 
        private MenuItem GetMenuItemFromHandleId(IntPtr hmenu, int item) {
            MenuItem mi = null;
            int id = UnsafeNativeMethods.GetMenuItemID(new HandleRef(null, hmenu), item);
            if (id == unchecked((int)0xFFFFFFFF)) {
                IntPtr childMenu = IntPtr.Zero;
                childMenu = UnsafeNativeMethods.GetSubMenu(new HandleRef(null, hmenu), item);
                int count = UnsafeNativeMethods.GetMenuItemCount(new HandleRef(null, childMenu));
                MenuItem found = null;
                for (int i=0; i<count; i++) {
                    found = GetMenuItemFromHandleId(childMenu, i);
                    if (found != null) {
                        Menu parent = found.Parent;
                        if (parent != null && parent is MenuItem) {
                            found = (MenuItem)parent;
                            break;
                        }
                        found = null;
                    }
                }
 
                mi = found;
            }
            else {
                Command cmd = Command.GetCommandFromID(id);
                if (cmd != null) {
                    Object reference = cmd.Target;
                    if (reference != null && reference is MenuItem.MenuItemData) {
                        mi = ((MenuItem.MenuItemData)reference).baseItem;
                    }
                }
            }
            return mi;
        }
 
        /// <devdoc>
        ///     - Returns child controls sorted according to their TabIndex property order.
        ///     - Controls with the same TabIndex remain in original relative child index order (= z-order).
        ///     - Returns a TabIndex sorted array of ControlTabOrderHolder objects.
        /// </devdoc>
        private ArrayList GetChildControlsTabOrderList(bool handleCreatedOnly) {
            ArrayList holders = new ArrayList();
 
            foreach (Control c in Controls) {
                if (!handleCreatedOnly || c.IsHandleCreated) {
                    holders.Add(new ControlTabOrderHolder(holders.Count, c.TabIndex, c));
                }
            }
 
            holders.Sort(new ControlTabOrderComparer());
 
            return holders;
        }
 
        /// <devdoc>
        ///     - Returns native child windows sorted according to their TabIndex property order.
        ///     - Controls with the same TabIndex remain in original relative child index order (= z-order).
        ///     - Child windows with no corresponding Control objects (and therefore no discernable TabIndex)
        ///       are sorted to the front of the list (but remain in relative z-order to one another).
        ///     - This version returns a sorted array of integers, representing the original z-order
        ///       based indexes of the native child windows.
        /// </devdoc>
        private int[] GetChildWindowsInTabOrder() {
            ArrayList holders = GetChildWindowsTabOrderList();
 
            int[] indexes = new int[holders.Count];
 
            for (int i = 0; i < holders.Count; i++) {
                indexes[i] = ((ControlTabOrderHolder) holders[i]).oldOrder;
            }
 
            return indexes;
        }
 
        /// <devdoc>
        ///     - Returns child controls sorted according to their TabIndex property order.
        ///     - Controls with the same TabIndex remain in original relative child index order (= z-order).
        ///     - This version returns a sorted array of control references.
        /// </devdoc>
        internal Control[] GetChildControlsInTabOrder(bool handleCreatedOnly) {
            ArrayList holders = GetChildControlsTabOrderList(handleCreatedOnly);
 
            Control[] ctls = new Control[holders.Count];
 
            for (int i = 0; i < holders.Count; i++) {
                ctls[i] = ((ControlTabOrderHolder) holders[i]).control;
            }
 
            return ctls;
        }
 
        /// <devdoc>
        ///      This class contains a control and associates it with a z-order.
        ///      This is used when sorting controls based on tab index first,
        ///      z-order second.
        /// </devdoc>
        private class ControlTabOrderHolder {
            internal readonly int oldOrder;
            internal readonly int newOrder;
            internal readonly Control control;
 
            internal ControlTabOrderHolder(int oldOrder, int newOrder, Control control) {
                this.oldOrder = oldOrder;
                this.newOrder = newOrder;
                this.control  = control;
            }
        }
 
        /// <devdoc>
        ///      Used to sort controls based on tab index and z-order.
        /// </devdoc>
        private class ControlTabOrderComparer : IComparer {
            int IComparer.Compare(Object x, Object y) {
                ControlTabOrderHolder hx = (ControlTabOrderHolder) x;
                ControlTabOrderHolder hy = (ControlTabOrderHolder) y;
 
                int delta = hx.newOrder - hy.newOrder;
                if (delta == 0)
                    delta = hx.oldOrder - hy.oldOrder;
 
                return delta;
            }
        }
 
        /// <devdoc>
        ///     Given a native window handle, returns array of handles to window's children (in z-order).
        /// </devdoc>
        private static ArrayList GetChildWindows(IntPtr hWndParent) {
            ArrayList windows = new ArrayList();
 
            for (IntPtr hWndChild = UnsafeNativeMethods.GetWindow(new HandleRef(null, hWndParent), NativeMethods.GW_CHILD);
                 hWndChild != IntPtr.Zero;
                 hWndChild = UnsafeNativeMethods.GetWindow(new HandleRef(null, hWndChild), NativeMethods.GW_HWNDNEXT)) {
                windows.Add(hWndChild);
            }
 
            return windows;
        }
 
        /// <devdoc>
        ///     - Returns native child windows sorted according to their TabIndex property order.
        ///     - Controls with the same TabIndex remain in original relative child index order (= z-order).
        ///     - Child windows with no corresponding Control objects (and therefore no discernable TabIndex)
        ///       are sorted to the front of the list (but remain in relative z-order to one another).
        ///     - Returns a TabIndex sorted array of ControlTabOrderHolder objects.
        /// </devdoc>
        private ArrayList GetChildWindowsTabOrderList() {
            ArrayList holders = new ArrayList();
            ArrayList windows = GetChildWindows(this.Handle);
 
            foreach (IntPtr hWnd in windows) {
                Control ctl = FromHandleInternal(hWnd);
                int tabIndex = (ctl == null) ? -1 : ctl.TabIndex;
                holders.Add(new ControlTabOrderHolder(holders.Count, tabIndex, ctl));
            }
 
            holders.Sort(new ControlTabOrderComparer());
 
            return holders;
        }
 
        // 
 
        internal virtual Control GetFirstChildControlInTabOrder(bool forward) {
         
            ControlCollection ctlControls = (ControlCollection)this.Properties.GetObject(PropControlsCollection);
 
            Control found = null;
            if (ctlControls != null) {
                 if (forward) { 
                    for (int c = 0; c < ctlControls.Count; c++) {
                        if (found == null || found.tabIndex > ctlControls[c].tabIndex) {
                            found = ctlControls[c];
                        }
                    }
                 }
                 else {
                    
                    // Cycle through the controls in reverse z-order looking for the one with the highest
                    // tab index.
                    //
                    for (int c = ctlControls.Count - 1; c >= 0; c--) {
                        if (found == null || found.tabIndex < ctlControls[c].tabIndex) {
                            found = ctlControls[c];
                        }
                    }
                 }
            }
            return found;
 
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.GetNextControl"]/*' />
        /// <devdoc>
        ///     Retrieves the next control in the tab order of child controls.
        /// </devdoc>
        public Control GetNextControl(Control ctl, bool forward) {
            if (!Contains(ctl)) {
                ctl = this;
            }
 
            if (forward) {
                ControlCollection ctlControls = (ControlCollection)ctl.Properties.GetObject(PropControlsCollection);
 
                if (ctlControls != null && ctlControls.Count > 0 && (ctl == this || !IsFocusManagingContainerControl(ctl))) {
                    Control found = ctl.GetFirstChildControlInTabOrder(/*forward=*/true);
                    if (found != null) {
                        return found;
                    }
                }
 
                while (ctl != this) {
                    int targetIndex = ctl.tabIndex;
                    bool hitCtl = false;
                    Control found = null;
                    Control p = ctl.parent;
 
                    // Cycle through the controls in z-order looking for the one with the next highest
                    // tab index.  Because there can be dups, we have to start with the existing tab index and
                    // remember to exclude the current control.
                    //
                    int parentControlCount = 0;
 
                    ControlCollection parentControls = (ControlCollection)p.Properties.GetObject(PropControlsCollection);
 
                    if (parentControls != null) {
                        parentControlCount = parentControls.Count;
                    }
 
                    for (int c = 0; c < parentControlCount; c++) {
 
                        // The logic for this is a bit lengthy, so I have broken it into separate
                        // caluses:
 
                        // We are not interested in ourself.
                        //
                        if (parentControls[c] != ctl) {
 
                            // We are interested in controls with >= tab indexes to ctl.  We must include those
                            // controls with equal indexes to account for duplicate indexes.
                            //
                            if (parentControls[c].tabIndex >= targetIndex) {
 
                                // Check to see if this control replaces the "best match" we've already
                                // found.
                                //
                                if (found == null || found.tabIndex > parentControls[c].tabIndex) {
 
                                    // Finally, check to make sure that if this tab index is the same as ctl,
                                    // that we've already encountered ctl in the z-order.  If it isn't the same,
                                    // than we're more than happy with it.
                                    //
                                    if (parentControls[c].tabIndex != targetIndex || hitCtl) {
                                        found = parentControls[c];
                                    }
                                }
                            }
                        }
                        else {
                            // We track when we have encountered "ctl".  We never want to select ctl again, but
                            // we want to know when we've seen it in case we find another control with the same tab index.
                            //
                            hitCtl = true;
                        }
                    }
 
                    if (found != null) {
                        return found;
                    }
 
                    ctl = ctl.parent;
                }
            }
            else {
                if (ctl != this) {
 
                    int targetIndex = ctl.tabIndex;
                    bool hitCtl = false;
                    Control found = null;
                    Control p = ctl.parent;
 
                    // Cycle through the controls in reverse z-order looking for the next lowest tab index.  We must
                    // start with the same tab index as ctl, because there can be dups.
                    //
                    int parentControlCount = 0;
 
                    ControlCollection parentControls = (ControlCollection)p.Properties.GetObject(PropControlsCollection);
 
                    if (parentControls != null) {
                        parentControlCount = parentControls.Count;
                    }
 
                    for (int c = parentControlCount - 1; c >= 0; c--) {
 
                        // The logic for this is a bit lengthy, so I have broken it into separate
                        // caluses:
 
                        // We are not interested in ourself.
                        //
                        if (parentControls[c] != ctl) {
 
                            // We are interested in controls with <= tab indexes to ctl.  We must include those
                            // controls with equal indexes to account for duplicate indexes.
                            //
                            if (parentControls[c].tabIndex <= targetIndex) {
 
                                // Check to see if this control replaces the "best match" we've already
                                // found.
                                //
                                if (found == null || found.tabIndex < parentControls[c].tabIndex) {
 
                                    // Finally, check to make sure that if this tab index is the same as ctl,
                                    // that we've already encountered ctl in the z-order.  If it isn't the same,
                                    // than we're more than happy with it.
                                    //
                                    if (parentControls[c].tabIndex != targetIndex || hitCtl) {
                                        found = parentControls[c];
                                    }
                                }
                            }
                        }
                        else {
                            // We track when we have encountered "ctl".  We never want to select ctl again, but
                            // we want to know when we've seen it in case we find another control with the same tab index.
                            //
                            hitCtl = true;
                        }
                    }
 
                    // If we were unable to find a control we should return the control's parent.  However, if that parent is us, return
                    // NULL.
                    //
                    if (found != null) {
                        ctl = found;
                    }
                    else {
                        if (p == this) {
                            return null;
                        }
                        else {
                            return p;
                        }
                    }
                }
 
                // We found a control.  Walk into this control to find the proper sub control within it to select.
                //
                ControlCollection ctlControls = (ControlCollection)ctl.Properties.GetObject(PropControlsCollection);
 
                while (ctlControls != null && ctlControls.Count > 0 && (ctl == this || !IsFocusManagingContainerControl(ctl))) {
                    Control found = ctl.GetFirstChildControlInTabOrder(/*forward=*/false);
                    if (found != null) {
                        ctl = found;
                        ctlControls = (ControlCollection)ctl.Properties.GetObject(PropControlsCollection);
                    }
                    else {
                        break;
                    }
                }
            }
 
            return ctl == this? null: ctl;
        }
 
        /// <devdoc>
        ///     Return ((Control) window).Handle if window is a Control.
        ///     Otherwise, demands permission for AllWindows and returns window.Handle
        /// </devdoc>
        internal static IntPtr GetSafeHandle(IWin32Window window)
        {
            Debug.Assert(window != null, "window is null in Control.GetSafeHandle");
            IntPtr hWnd = IntPtr.Zero;
            Control control = window as Control;
            if (control != null) {
                hWnd = control.Handle;
                Debug.Assert(hWnd == IntPtr.Zero || UnsafeNativeMethods.IsWindow(new HandleRef(null, hWnd)));
                return hWnd;
            }
            else {
                IntSecurity.AllWindows.Demand();
                hWnd = window.Handle;
                if (hWnd == IntPtr.Zero || UnsafeNativeMethods.IsWindow(new HandleRef(null, hWnd))) {
                    return hWnd;
                }
                else {
                    throw new Win32Exception(NativeMethods.ERROR_INVALID_HANDLE);
                }
            }
        }
 
        /// <devdoc>
        ///     Retrieves the current value of the specified bit in the control's state.
        /// </devdoc>
        internal bool GetState(int flag) {
            return(state & flag) != 0;
        }
 
        /// <devdoc>
        ///     Retrieves the current value of the specified bit in the control's state2.
        /// </devdoc>
        private bool GetState2(int flag)
        {
            return (state2 & flag) != 0;
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.GetStyle"]/*' />
        /// <devdoc>
        ///     Retrieves the current value of the specified bit in the control's style.
        ///     NOTE: This is control style, not the Win32 style of the hWnd.
        /// </devdoc>
        protected bool GetStyle(ControlStyles flag) {
            return (controlStyle & flag) == flag;
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Hide"]/*' />
        /// <devdoc>
        ///     Hides the control by setting the visible property to false;
        /// </devdoc>
        public void Hide() {
            Visible = false;
        }
 
 
        /// <devdoc>
        ///     Sets up the TrackMouseEvent for listening for the
        ///     mouse leave event.
        /// </devdoc>
        /// <internalonly/>
        private void HookMouseEvent() {
            if (!GetState(STATE_TRACKINGMOUSEEVENT)) {
                SetState(STATE_TRACKINGMOUSEEVENT, true);
 
                if (trackMouseEvent == null) {
                    trackMouseEvent = new NativeMethods.TRACKMOUSEEVENT();
                    trackMouseEvent.dwFlags = NativeMethods.TME_LEAVE | NativeMethods.TME_HOVER;
                    trackMouseEvent.hwndTrack = Handle;
                }
 
                SafeNativeMethods.TrackMouseEvent(trackMouseEvent);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.InitLayout"]/*' />
        /// <devdoc>
        ///     Called after the control has been added to another container.
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual void InitLayout() {
            LayoutEngine.InitLayout(this, BoundsSpecified.All);
        }
 
        /// <devdoc>
        ///     This method initializes the scaling bits for this control based on
        ///     the bounds.
        /// </devdoc>
        private void InitScaling(BoundsSpecified specified) {
            requiredScaling |= (byte)((int)specified & RequiredScalingMask);
        }
 
        // Sets the text and background colors of the DC, and returns the background HBRUSH.
        // This gets called from some variation on WM_CTLCOLOR...
        // Virtual because Scrollbar insists on being different.
        //
        // NOTE: this message may not have originally been sent to this HWND.
        //
 
        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
        internal virtual IntPtr InitializeDCForWmCtlColor (IntPtr dc, int msg) {
            if (!GetStyle(ControlStyles.UserPaint)) {
                SafeNativeMethods.SetTextColor(new HandleRef(null, dc), ColorTranslator.ToWin32(ForeColor));
                SafeNativeMethods.SetBkColor(new HandleRef(null, dc), ColorTranslator.ToWin32(BackColor));
                return BackColorBrush;
            }
            else {
                return UnsafeNativeMethods.GetStockObject(NativeMethods.HOLLOW_BRUSH);
            }
        }
 
        #if WIN95_SUPPORT
        /// <devdoc>
        ///     Initializes mouse wheel support. This may involve registering some windows
        ///     messages on older operating systems.
        /// </devdoc>
        /// <internalonly/>
        private void InitMouseWheelSupport() {
            if (!mouseWheelInit) {
                // If we are running on less than NT4 or less that Win98 then we must use
                // the manual mousewheel stuff...
                //
                mouseWheelRoutingNeeded = !SystemInformation.NativeMouseWheelSupport;
 
                if (mouseWheelRoutingNeeded) {
                    IntPtr hwndMouseWheel = IntPtr.Zero;
 
                    // Check for the MouseZ "service". This is a little app that generated the
                    // MSH_MOUSEWHEEL messages by monitoring the hardware. If this app isn't
                    // found, then there is no support for MouseWheels on the system.
                    //
                    hwndMouseWheel = UnsafeNativeMethods.FindWindow(NativeMethods.MOUSEZ_CLASSNAME, NativeMethods.MOUSEZ_TITLE);
 
                    if (hwndMouseWheel != IntPtr.Zero) {
 
                        // Register the MSH_MOUSEWHEEL message... we look for this in the
                        // wndProc, and treat it just like WM_MOUSEWHEEL.
                        //
                        int message = SafeNativeMethods.RegisterWindowMessage(NativeMethods.MSH_MOUSEWHEEL);
 
                        if (message != 0) {
                            mouseWheelMessage = message;
                        }
                    }
                }
                mouseWheelInit = true;
            }
        }
        #endif
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Invalidate"]/*' />
        /// <devdoc>
        ///     Invalidates a region of the control and causes a paint message
        ///     to be sent to the control. This will not force a synchronous paint to
        ///     occur, calling update after invalidate will force a
        ///     synchronous paint.
        /// </devdoc>
        public void Invalidate(Region region) {
            Invalidate(region, false);
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Invalidate1"]/*' />
        /// <devdoc>
        ///     Invalidates a region of the control and causes a paint message
        ///     to be sent to the control. This will not force a synchronous paint to
        ///     occur, calling update after invalidate will force a
        ///     synchronous paint.
        /// </devdoc>
        public void Invalidate(Region region, bool invalidateChildren) {
            if (region == null) {
                Invalidate(invalidateChildren);
            }
            else if (IsHandleCreated) {
                IntPtr regionHandle = GetHRgn(region);
 
                try {
                    Debug.Assert(regionHandle != IntPtr.Zero, "Region wasn't null but HRGN is?");
                    if (invalidateChildren) {
                        SafeNativeMethods.RedrawWindow(new HandleRef(this, Handle),
                                                       null, new HandleRef(region, regionHandle),
                                                       NativeMethods.RDW_INVALIDATE |
                                                       NativeMethods.RDW_ERASE |
                                                       NativeMethods.RDW_ALLCHILDREN);
                    }
                    else {
                        // It's safe to invoke InvalidateRgn from a separate thread.
                        using (new MultithreadSafeCallScope())
                        {
                            SafeNativeMethods.InvalidateRgn(new HandleRef(this, Handle),
                                                            new HandleRef(region, regionHandle),
                                                            !GetStyle(ControlStyles.Opaque));
                        }
                    }
                }
                finally {
                    SafeNativeMethods.DeleteObject(new HandleRef(region, regionHandle));
                }
 
                Rectangle bounds = Rectangle.Empty;
 
                // gpr: We shouldn't have to create a Graphics for this...
                using (Graphics graphics = CreateGraphicsInternal()) {
                    bounds = Rectangle.Ceiling(region.GetBounds(graphics));
                }
                
                OnInvalidated(new InvalidateEventArgs(bounds));
            }
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Invalidate2"]/*' />
        /// <devdoc>
        ///     Invalidates the control and causes a paint message to be sent to the control.
        ///     This will not force a synchronous paint to occur, calling update after
        ///     invalidate will force a synchronous paint.
        /// </devdoc>
        public void Invalidate() {
            Invalidate(false);
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Invalidate3"]/*' />
        /// <devdoc>
        ///     Invalidates the control and causes a paint message to be sent to the control.
        ///     This will not force a synchronous paint to occur, calling update after
        ///     invalidate will force a synchronous paint.
        /// </devdoc>
        public void Invalidate(bool invalidateChildren) {
            if (IsHandleCreated) {
                if (invalidateChildren) {
                    SafeNativeMethods.RedrawWindow(new HandleRef(window, Handle),
                                                   null, NativeMethods.NullHandleRef,
                                                   NativeMethods.RDW_INVALIDATE |
                                                   NativeMethods.RDW_ERASE |
                                                   NativeMethods.RDW_ALLCHILDREN);
                }
                else {
                    // It's safe to invoke InvalidateRect from a separate thread.
                    using (new MultithreadSafeCallScope())
                    {
                        SafeNativeMethods.InvalidateRect(new HandleRef(window, Handle),
                                                         null,
                                                         (controlStyle & ControlStyles.Opaque) != ControlStyles.Opaque);
                    }
                }
 
                NotifyInvalidate(this.ClientRectangle);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Invalidate4"]/*' />
        /// <devdoc>
        ///     Invalidates a rectangular region of the control and causes a paint message
        ///     to be sent to the control. This will not force a synchronous paint to
        ///     occur, calling update after invalidate will force a
        ///     synchronous paint.
        /// </devdoc>
        public void Invalidate(Rectangle rc) {
            Invalidate(rc, false);
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Invalidate5"]/*' />
        /// <devdoc>
        ///     Invalidates a rectangular region of the control and causes a paint message
        ///     to be sent to the control. This will not force a synchronous paint to
        ///     occur, calling update after invalidate will force a
        ///     synchronous paint.
        /// </devdoc>
        public void Invalidate(Rectangle rc, bool invalidateChildren) {
            if (rc.IsEmpty) {
                Invalidate(invalidateChildren);
            }
            else if (IsHandleCreated) {
                if (invalidateChildren) {
                    NativeMethods.RECT rcArea = NativeMethods.RECT.FromXYWH(rc.X, rc.Y, rc.Width, rc.Height);
                    SafeNativeMethods.RedrawWindow(new HandleRef(window, Handle),
                                                   ref rcArea, NativeMethods.NullHandleRef,
                                                   NativeMethods.RDW_INVALIDATE |
                                                   NativeMethods.RDW_ERASE |
                                                   NativeMethods.RDW_ALLCHILDREN);
                }
                else {
                    NativeMethods.RECT rcArea =
                        NativeMethods.RECT.FromXYWH(rc.X, rc.Y, rc.Width,
                                                    rc.Height);
 
                    // It's safe to invoke InvalidateRect from a separate thread.
                    using (new MultithreadSafeCallScope())
                    {
                        SafeNativeMethods.InvalidateRect(new HandleRef(window, Handle),
                                                         ref rcArea,
                                                         (controlStyle & ControlStyles.Opaque) != ControlStyles.Opaque);
                    }
                }
                NotifyInvalidate(rc);
            }
        }
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Invoke"]/*' />
        /// <devdoc>
        ///     Executes the given delegate on the thread that owns this Control's
        ///     underlying window handle.  It is an error to call this on the same thread that
        ///     the control belongs to.  If the control's handle doesn't exist yet, this will
        ///     follow up the control's parent chain until it finds a control or form that does
        ///     have a window handle.  If no appropriate handle can be found, invoke will throw
        ///     an exception.  Exceptions that are raised during the call will be
        ///     propapgated back to the caller.
        ///
        ///     There are five functions on a control that are safe to call from any
        ///     thread:  GetInvokeRequired, Invoke, BeginInvoke, EndInvoke and CreateGraphics.
        ///     For all other method calls, you should use one of the invoke methods to marshal
        ///     the call to the control's thread.
        /// </devdoc>
        public Object Invoke(Delegate method) {
            return Invoke(method, null);
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.Invoke1"]/*' />
        /// <devdoc>
        ///     Executes the given delegate on the thread that owns this Control's
        ///     underlying window handle.  It is an error to call this on the same thread that
        ///     the control belongs to.  If the control's handle doesn't exist yet, this will
        ///     follow up the control's parent chain until it finds a control or form that does
        ///     have a window handle.  If no appropriate handle can be found, invoke will throw
        ///     an exception.  Exceptions that are raised during the call will be
        ///     propapgated back to the caller.
        ///
        ///     There are five functions on a control that are safe to call from any
        ///     thread:  GetInvokeRequired, Invoke, BeginInvoke, EndInvoke and CreateGraphics.
        ///     For all other method calls, you should use one of the invoke methods to marshal
        ///     the call to the control's thread.
        /// </devdoc>
        public Object Invoke(Delegate method, params Object[] args) {
            using (new MultithreadSafeCallScope()) {
                Control marshaler = FindMarshalingControl();
                return marshaler.MarshaledInvoke(this, method, args, true);
            }
        }
 
        /// <devdoc>
        ///     Perform the callback of a particular ThreadMethodEntry - called by InvokeMarshaledCallbacks below.
        ///
        ///     If the invoke request originated from another thread, we should have already captured the ExecutionContext
        ///     of that thread. The callback is then invoked using that ExecutionContext (which includes info like the
        ///     compressed security stack).
        ///
        ///     NOTE: The one part of the ExecutionContext that we DONT want applied to the callback is its SyncContext,
        ///     since this is the SyncContext of the other thread. So we grab the SyncContext of OUR thread, and pass
        ///     this through to the callback to use instead.
        ///
        ///     When the invoke request comes from this thread, there won't be an ExecutionContext so we just invoke
        ///     the callback as is.
        /// </devdoc>
        private void InvokeMarshaledCallback(ThreadMethodEntry tme){
            if (tme.executionContext != null) {
                if (invokeMarshaledCallbackHelperDelegate == null) {
                    invokeMarshaledCallbackHelperDelegate = new ContextCallback(InvokeMarshaledCallbackHelper);
                }
                // If there's no ExecutionContext, make sure we have a SynchronizationContext.  There's no
                // direct check for ExecutionContext: this is as close as we can get.
                if (SynchronizationContext.Current == null) {
                    WindowsFormsSynchronizationContext.InstallIfNeeded();
                }
 
                tme.syncContext = SynchronizationContext.Current;
                ExecutionContext.Run(tme.executionContext, invokeMarshaledCallbackHelperDelegate, tme);
            }
            else {
                InvokeMarshaledCallbackHelper(tme);
            }
        }
 
        /// <devdoc>
        ///     Worker for invoking marshaled callbacks.
        /// </devdoc>
        private static void InvokeMarshaledCallbackHelper(object obj)
        {
            ThreadMethodEntry tme = (ThreadMethodEntry) obj;
 
            if (tme.syncContext != null) {
                SynchronizationContext oldContext = SynchronizationContext.Current;
 
                try {
                    SynchronizationContext.SetSynchronizationContext(tme.syncContext);
 
                    InvokeMarshaledCallbackDo(tme);
                }
                finally {
                    SynchronizationContext.SetSynchronizationContext(oldContext);
                }
            }
            else {
                InvokeMarshaledCallbackDo(tme);
            }
        }
 
        /// <devdoc>
        /// </devdoc>
        private static void InvokeMarshaledCallbackDo(ThreadMethodEntry tme)
        {
            // We short-circuit a couple of common cases for speed.
            //
            if (tme.method is EventHandler) {
                if (tme.args == null || tme.args.Length < 1) {
                    ((EventHandler)tme.method)(tme.caller, EventArgs.Empty);
                }
                else if (tme.args.Length < 2) {
                    ((EventHandler)tme.method)(tme.args[0], EventArgs.Empty);
                }
                else {
                    ((EventHandler)tme.method)(tme.args[0], (EventArgs)tme.args[1]);
                }
            }
            else if (tme.method is MethodInvoker) {
                ((MethodInvoker)tme.method)();
            }
            else if (tme.method is WaitCallback)
            {
                Debug.Assert(tme.args.Length == 1,
                             "Arguments are wrong for WaitCallback");
                ((WaitCallback)tme.method)(tme.args[0]);
            }
            else {
                tme.retVal = tme.method.DynamicInvoke(tme.args);
            }
        }
 
        /// <devdoc>
        ///     Called on the control's owning thread to perform the actual callback.
        ///     This empties this control's callback queue, propagating any exceptions
        ///     back as needed.
        /// </devdoc>
        private void InvokeMarshaledCallbacks() {
            ThreadMethodEntry current = null;
            lock(threadCallbackList) {
                if (threadCallbackList.Count > 0) {
                    current = (ThreadMethodEntry)threadCallbackList.Dequeue();
                }
            }
 
            // Now invoke on all the queued items.
            //
            while (current != null) {
                if (current.method != null) {
 
                    try {
                        // If we are running under the debugger, don't wrap asynchronous
                        // calls in a try catch.  It is much better to throw here than pop up
                        // a thread exception dialog below.
                        if (NativeWindow.WndProcShouldBeDebuggable  && !current.synchronous) {
                            InvokeMarshaledCallback(current);
                        }
                        else {
                            try {
                                InvokeMarshaledCallback(current);
                            }
                            catch (Exception t) {
                                current.exception = t.GetBaseException();
                            }
                        }
                    }
                    finally {
                        current.Complete();
 
                        // This code matches the behavior above.  Basically, if we're debugging, don't
                        // do this because the exception would have been handled above.  If we're
                        // not debugging, raise the exception here.
                        if (!NativeWindow.WndProcShouldBeDebuggable &&
                            current.exception != null && !current.synchronous) {
                            Application.OnThreadException(current.exception);
                        }
                    }
                }
 
                lock (threadCallbackList) {
                    if (threadCallbackList.Count > 0) {
                        current = (ThreadMethodEntry)threadCallbackList.Dequeue();
                    }
                    else {
                        current = null;
                    }
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.InvokePaint"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected void InvokePaint(Control c, PaintEventArgs e) {
            c.OnPaint(e);
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.InvokePaintBackground"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected void InvokePaintBackground(Control c, PaintEventArgs e) {
           c.OnPaintBackground(e);
        }
 
        /// <devdoc>
        /// determines whether the font is set
        /// </devdoc>
        /// <internalonly/>
        internal bool IsFontSet() {
            Font font = (Font)Properties.GetObject(PropFont);
            if (font != null) {
                return true;
            }
            return false;
        }
 
        /// <devdoc>
        ///     WARNING! The meaning of this method is not what it appears.
        ///     The method returns true if "descendant" (the argument) is a descendant
        ///     of "this". I'd expect it to be the other way around, but oh well too late.
        /// </devdoc>
        /// <internalonly/>
        internal bool IsDescendant(Control descendant) {
            Control control = descendant;
            while (control != null) {
                if (control == this)
                    return true;
                control = control.ParentInternal;
            }
            return false;
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.IsKeyLocked"]/*' />
        /// <devdoc>
        /// This Function will return a Boolean as to whether the Key value passed in is Locked...
        /// </devdoc>
        public static bool IsKeyLocked(Keys keyVal) {
            if (keyVal == Keys.Insert || keyVal == Keys.NumLock || keyVal == Keys.CapsLock || keyVal == Keys.Scroll) {
                int result = UnsafeNativeMethods.GetKeyState((int)keyVal);
 
                // If the high-order bit is 1, the key is down; otherwise, it is up.
                // If the low-order bit is 1, the key is toggled. A key, such as the CAPS LOCK key,
                // is toggled if it is turned on. The key is off and untoggled if the low-order bit is 0.
                // A toggle key's indicator light (if any) on the keyboard will be on when the key is toggled,
                // and off when the key is untoggled.
 
                // Toggle keys (only low bit is of interest).
                if( keyVal == Keys.Insert || keyVal == Keys.CapsLock )
                {
                    return (result & 0x1) != 0x0;
                }
 
                return (result & 0x8001) != 0x0;
            }
 
            // else - it's an un-lockable key.
            // VSWhidbey 95660: Actually get the exception string from the system resource.
            throw new NotSupportedException(SR.GetString(SR.ControlIsKeyLockedNumCapsScrollLockKeysSupportedOnly));
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.IsInputChar"]/*' />
        /// <devdoc>
        ///     Determines if charCode is an input character that the control
        ///     wants. This method is called during window message pre-processing to
        ///     determine whether the given input character should be pre-processed or
        ///     sent directly to the control. If isInputChar returns true, the
        ///     given character is sent directly to the control. If isInputChar
        ///     returns false, the character is pre-processed and only sent to the
        ///     control if it is not consumed by the pre-processing phase. The
        ///     pre-processing of a character includes checking whether the character
        ///     is a mnemonic of another control.
        /// </devdoc>
        
        // SECREVIEW:
        // NOT LinkDemanding here because these functions do not have a processing side effect
        // by directly calling them.
        [UIPermission(SecurityAction.InheritanceDemand, Window=UIPermissionWindow.AllWindows)]
        protected virtual bool IsInputChar(char charCode) {
            Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "Control.IsInputChar 0x" + ((int)charCode).ToString("X", CultureInfo.InvariantCulture));
 
            int mask = 0;
            if (charCode == (char)(int)Keys.Tab) {
                mask = NativeMethods.DLGC_WANTCHARS | NativeMethods.DLGC_WANTALLKEYS | NativeMethods.DLGC_WANTTAB;
            }
            else {
                mask = NativeMethods.DLGC_WANTCHARS | NativeMethods.DLGC_WANTALLKEYS;
            }
            return(unchecked( (int) (long)SendMessage(NativeMethods.WM_GETDLGCODE, 0, 0)) & mask) != 0;
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.IsInputKey"]/*' />
        /// <devdoc>
        ///     Determines if keyData is an input key that the control wants.
        ///     This method is called during window message pre-processing to determine
        ///     whether the given input key should be pre-processed or sent directly to
        ///     the control. If isInputKey returns true, the given key is sent
        ///     directly to the control. If isInputKey returns false, the key is
        ///     pre-processed and only sent to the control if it is not consumed by the
        ///     pre-processing phase. Keys that are pre-processed include TAB, RETURN,
        ///     ESCAPE, and arrow keys.
        /// </devdoc>
 
        // SECREVIEW:
        // NOT LinkDemanding here because these functions do not have a processing side effect
        // by directly calling them.
        [UIPermission(SecurityAction.InheritanceDemand, Window=UIPermissionWindow.AllWindows)]
        protected virtual bool IsInputKey(Keys keyData) {
            Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "Control.IsInputKey " + keyData.ToString());
 
            if ((keyData & Keys.Alt) == Keys.Alt) return false;
            int mask = NativeMethods.DLGC_WANTALLKEYS;
            switch (keyData & Keys.KeyCode) {
                case Keys.Tab:
                    mask = NativeMethods.DLGC_WANTALLKEYS | NativeMethods.DLGC_WANTTAB;
                    break;
                case Keys.Left:
                case Keys.Right:
                case Keys.Up:
                case Keys.Down:
                    mask = NativeMethods.DLGC_WANTALLKEYS | NativeMethods.DLGC_WANTARROWS;
                    break;
            }
 
            if (IsHandleCreated) {
                return(unchecked( (int) (long)SendMessage(NativeMethods.WM_GETDLGCODE, 0, 0)) & mask) != 0;
            }
            else {
                return false;
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.IsMnemonic"]/*' />
        /// <devdoc>
        ///     Determines if charCode is the mnemonic character in text.
        ///     The mnemonic character is the character imediately following the first
        ///     instance of "&amp;" in text
        /// </devdoc>
        public static bool IsMnemonic(char charCode, string text) {
#if DEBUG
            if (ControlKeyboardRouting.TraceVerbose) {
                Debug.Write("Control.IsMnemonic(" + charCode.ToString() + ", ");
 
                if (text != null) {
                    Debug.Write(text);
                }
                else {
                    Debug.Write("null");
                }
                Debug.WriteLine(")");
            }
#endif
 
            //Special case handling:
            if (charCode=='&') {
                Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "   ...returning false");
                return false;
            } //if
 
 
            if (text != null) {
                int pos = -1; // start with -1 to handle double &'s
                char c2 = Char.ToUpper(charCode, CultureInfo.CurrentCulture);
                for (;;) {
                    if (pos + 1 >= text.Length)
                        break;
                    pos = text.IndexOf('&', pos + 1) + 1;
                    if (pos <= 0 || pos >= text.Length)
                        break;
                    char c1 = Char.ToUpper(text[pos], CultureInfo.CurrentCulture);
                    Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "   ...& found... char=" + c1.ToString());
                    if (c1 == c2 || Char.ToLower(c1, CultureInfo.CurrentCulture) == Char.ToLower(c2, CultureInfo.CurrentCulture)) {
                        Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "   ...returning true");
                        return true;
                    }
                }
                Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose && pos == 0, "   ...no & found");
            }
            Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "   ...returning false");
            return false;
        }
 
        private void ListenToUserPreferenceChanged(bool listen) {
            if (GetState2(STATE2_LISTENINGTOUSERPREFERENCECHANGED)) {
                if (!listen) {
                    SetState2(STATE2_LISTENINGTOUSERPREFERENCECHANGED, false);
                    SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(this.UserPreferenceChanged);
                }
            }
            else if (listen) {
                SetState2(STATE2_LISTENINGTOUSERPREFERENCECHANGED, true);
                SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(this.UserPreferenceChanged);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.LogicalToDeviceUnits"]/*' />
        /// <devdoc>
        /// Transforms an integer coordinate from logical to device units
        /// by scaling it for the current DPI and rounding down to the nearest integer value.
        /// </devdoc>
        public int LogicalToDeviceUnits(int value) {
            return DpiHelper.LogicalToDeviceUnits(value, DeviceDpi);
        }
 
        /// <summary>
        /// Transforms size from logical to device units
        /// by scaling it for the current DPI and rounding down to the nearest integer value for width and height.
        /// </summary>
        /// <param name="value"> size to be scaled</param>
        /// <returns> scaled size</returns>
        public Size LogicalToDeviceUnits(Size value) {
            return DpiHelper.LogicalToDeviceUnits(value, DeviceDpi);
        }
 
        /// <summary>
        /// Create a new bitmap scaled for the device units.
        /// When displayed on the device, the scaled image will have same size as the original image would have when displayed at 96dpi.
        /// </summary>
        /// <param name="logicalBitmap">The image to scale from logical units to device units</param>
        public void ScaleBitmapLogicalToDevice(ref Bitmap logicalBitmap) {
            DpiHelper.ScaleBitmapLogicalToDevice(ref logicalBitmap, DeviceDpi);
        }
 
        internal void AdjustWindowRectEx(ref NativeMethods.RECT rect, int style, bool bMenu, int exStyle) { 
            if (DpiHelper.EnableDpiChangedMessageHandling) {
                SafeNativeMethods.AdjustWindowRectExForDpi(ref rect, style, bMenu, exStyle, (uint)deviceDpi);
            } else {
                SafeNativeMethods.AdjustWindowRectEx(ref rect, style, bMenu, exStyle);
            }
        }
 
        private Object MarshaledInvoke(Control caller, Delegate method, Object[] args, bool synchronous) {
 
            // Marshaling an invoke occurs in three steps:
            //
            // 1.  Create a ThreadMethodEntry that contains the packet of information
            //     about this invoke.  This TME is placed on a linked list of entries because
            //     we have a gap between the time we PostMessage and the time it actually
            //     gets processed, and this gap may allow other invokes to come in.  Access
            //     to this linked list is always synchronized.
            //
            // 2.  Post ourselves a message.  Our caller has already determined the
            //     best control to call us on, and we should almost always have a handle.
            //
            // 3.  If we're synchronous, wait for the message to get processed.  We don't do
            //     a SendMessage here so we're compatible with OLE, which will abort many
            //     types of calls if we're within a SendMessage.
            //
 
            if (!IsHandleCreated) {
                throw new InvalidOperationException(SR.GetString(SR.ErrorNoMarshalingThread));
            }
 
            // We have to demand unmanaged code permission here for the control hosted in
            // the browser case. Without this check, we will expose a security hole, because
            // ActiveXImpl.OnMessage() will assert unmanaged code for everyone as part of
            // its implementation.
            // The right fix is to remove the Assert() on top of the ActiveXImpl class, and
            // visit each method to see if it needs unmanaged code permission, and if so, add
            // the permission just to that method(s).
            //
            ActiveXImpl activeXImpl = (ActiveXImpl)Properties.GetObject(PropActiveXImpl);
            if (activeXImpl != null) {
                IntSecurity.UnmanagedCode.Demand();
            }
 
            // We don't want to wait if we're on the same thread, or else we'll deadlock.
            // It is important that syncSameThread always be false for asynchronous calls.
            //
            bool syncSameThread = false;
            int pid; // ignored
            if (SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(this, Handle), out pid) == SafeNativeMethods.GetCurrentThreadId()) {
                if (synchronous)
                    syncSameThread = true;
            }
 
            // Store the compressed stack information from the thread that is calling the Invoke()
            // so we can assign the same security context to the thread that will actually execute
            // the delegate being passed.
            //
            ExecutionContext executionContext = null;
            if (!syncSameThread) {
                executionContext = ExecutionContext.Capture();
            }
            ThreadMethodEntry tme = new ThreadMethodEntry(caller, this, method, args, synchronous, executionContext);
 
            lock (this) {
                if (threadCallbackList == null) {
                    threadCallbackList = new Queue();
                }
            }
 
            lock (threadCallbackList) {
                if (threadCallbackMessage == 0) {
                    threadCallbackMessage = SafeNativeMethods.RegisterWindowMessage(Application.WindowMessagesVersion + "_ThreadCallbackMessage");
                }
                threadCallbackList.Enqueue(tme);
            }
 
            if (syncSameThread) {
                InvokeMarshaledCallbacks();
            }  else {
                // 
 
                UnsafeNativeMethods.PostMessage(new HandleRef(this, Handle), threadCallbackMessage, IntPtr.Zero, IntPtr.Zero);
            }
 
            if (synchronous) {
                if (!tme.IsCompleted) {
                    WaitForWaitHandle(tme.AsyncWaitHandle);
                }
                if (tme.exception != null) {
                    throw tme.exception;
                }
                return tme.retVal;
            }
            else {
                return(IAsyncResult)tme;
            }
        }
 
        /// <devdoc>
        ///     This method is used by WM_GETCONTROLNAME and WM_GETCONTROLTYPE
        ///     to marshal a string to a message structure.  It handles
        ///     two cases:  if no buffer was passed it returns the size of
        ///     buffer needed.  If a buffer was passed, it fills the buffer.
        ///     If the passed buffer is not long enough it will return -1.
        /// </devdoc>
        private void MarshalStringToMessage(string value, ref Message m) {
            if (m.LParam == IntPtr.Zero) {
                m.Result = (IntPtr)((value.Length + 1) * Marshal.SystemDefaultCharSize);
                return;
            }
 
            if (unchecked((int)(long)m.WParam) < value.Length + 1) {
                m.Result = (IntPtr)(-1);
                return;
            }
 
            // Copy the name into the given IntPtr
            //
            char[] nullChar = new char[] {(char)0};
            byte[] nullBytes;
            byte[] bytes;
 
            if (Marshal.SystemDefaultCharSize == 1) {
                bytes = Encoding.Default.GetBytes(value);
                nullBytes = Encoding.Default.GetBytes(nullChar);
            }
            else {
                bytes = Encoding.Unicode.GetBytes(value);
                nullBytes = Encoding.Unicode.GetBytes(nullChar);
            }
 
            Marshal.Copy(bytes, 0, m.LParam, bytes.Length);
            Marshal.Copy(nullBytes, 0, unchecked((IntPtr)((long)m.LParam + (long)bytes.Length)), nullBytes.Length);
 
            m.Result = (IntPtr)((bytes.Length + nullBytes.Length)/Marshal.SystemDefaultCharSize);
        }
 
        // Used by form to notify the control that it has been "entered"
        //
        internal void NotifyEnter() {
            Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "Control::NotifyEnter() - " + this.Name);
            OnEnter(EventArgs.Empty);
        }
 
        // Used by form to notify the control that it has been "left"
        //
        internal void NotifyLeave() {
            Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "Control::NotifyLeave() - " + this.Name);
            OnLeave(EventArgs.Empty);
        }
 
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.NotifyInvalidate"]/*' />
        /// <internalonly/>
        /// <devdoc>
        ///    Propagates the invalidation event, notifying the control that
        ///    some part of it is being invalidated and will subsequently need
        ///    to repaint.
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual void NotifyInvalidate(Rectangle invalidatedArea) {
            OnInvalidated(new InvalidateEventArgs(invalidatedArea));
        }
 
        // Used by form to notify the control that it is validating.
        //
        private bool NotifyValidating() {
            CancelEventArgs ev = new CancelEventArgs();
            OnValidating(ev);
            return ev.Cancel;
        }
 
        // Used by form to notify the control that it has been validated.
        //
        private void NotifyValidated() {
            OnValidated(EventArgs.Empty);
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.InvokeOnClick"]/*' />
        /// <devdoc>
        /// <para>Raises the <see cref='System.Windows.Forms.Control.Click'/> event.</para>
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected void InvokeOnClick(Control toInvoke, EventArgs e) {
            if (toInvoke != null) {
                toInvoke.OnClick(e);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.OnAutoSizeChanged"]/*' />
        protected virtual void OnAutoSizeChanged(EventArgs e) {
            Contract.Requires(e != null);
            EventHandler eh = Events[EventAutoSizeChanged] as EventHandler;
            if (eh != null) {
                 eh(this, e);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.OnBackColorChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual void OnBackColorChanged(EventArgs e) {
            Contract.Requires(e != null);
            if (GetAnyDisposingInHierarchy()) {
                return;
            }
 
            object backBrush = Properties.GetObject(PropBackBrush);
            if (backBrush != null) {
                if (GetState(STATE_OWNCTLBRUSH)) {
                    IntPtr p = (IntPtr)backBrush;
                    if (p != IntPtr.Zero) {
                        SafeNativeMethods.DeleteObject(new HandleRef(this, p));
                    }
                }
                Properties.SetObject(PropBackBrush, null);
            }
 
            Invalidate();
 
            EventHandler eh = Events[EventBackColor] as EventHandler;
            if (eh != null) {
                 eh(this, e);
            }
 
            ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection);
            if (controlsCollection != null) {
                // PERFNOTE: This is more efficient than using Foreach.  Foreach
                // forces the creation of an array subset enum each time we
                // enumerate
                for(int i = 0; i < controlsCollection.Count; i++) {
                    controlsCollection[i].OnParentBackColorChanged(e);
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.OnBackgroundImageChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual void OnBackgroundImageChanged(EventArgs e) {
            Contract.Requires(e != null);
            if (GetAnyDisposingInHierarchy()) {
                return;
            }
 
            Invalidate();
 
            EventHandler eh = Events[EventBackgroundImage] as EventHandler;
            if (eh != null) {
                 eh(this, e);
            }
 
            ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection);
            if (controlsCollection != null) {
                // PERFNOTE: This is more efficient than using Foreach.  Foreach
                // forces the creation of an array subset enum each time we
                // enumerate
                for(int i = 0; i < controlsCollection.Count; i++) {
                    controlsCollection[i].OnParentBackgroundImageChanged(e);
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.OnBackgroundImageLayoutChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual void OnBackgroundImageLayoutChanged(EventArgs e) {
            Contract.Requires(e != null);
            if (GetAnyDisposingInHierarchy()) {
                return;
            }
 
            Invalidate();
 
            EventHandler eh = Events[EventBackgroundImageLayout] as EventHandler;
            if (eh != null) {
                 eh(this, e);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.OnBindingContextChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual void OnBindingContextChanged(EventArgs e) {
            Contract.Requires(e != null);
            if (Properties.GetObject(PropBindings) != null) {
                UpdateBindings();
            }
 
            EventHandler eh = Events[EventBindingContext] as EventHandler;
            if (eh != null) {
                 eh(this, e);
            }
 
            ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection);
            if (controlsCollection != null) {
                // PERFNOTE: This is more efficient than using Foreach.  Foreach
                // forces the creation of an array subset enum each time we
                // enumerate
                for(int i = 0; i < controlsCollection.Count; i++) {
                    controlsCollection[i].OnParentBindingContextChanged(e);
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.OnCausesValidationChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual void OnCausesValidationChanged(EventArgs e) {
            Contract.Requires(e != null);
            EventHandler eh = Events[EventCausesValidation] as EventHandler;
            if (eh != null) {
                 eh(this, e);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.OnChildLayoutResuming"]/*' />
        /// <devdoc>
        ///     Called when a child is about to resume its layout.  The default implementation
        ///     calls OnChildLayoutResuming on the parent.
        /// </devdoc>
        internal virtual void OnChildLayoutResuming(Control child, bool performLayout) {
            if (ParentInternal != null) {
                ParentInternal.OnChildLayoutResuming(child, performLayout);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.OnContextMenuChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual void OnContextMenuChanged(EventArgs e) {
            Contract.Requires(e != null);
            EventHandler eh = Events[EventContextMenu] as EventHandler;
            if (eh != null) {
                 eh(this, e);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.OnContextMenuStripChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual void OnContextMenuStripChanged(EventArgs e) {
            Contract.Requires(e != null);
            EventHandler eh = Events[EventContextMenuStrip] as EventHandler;
            if (eh != null) {
                eh(this, e);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.OnCursorChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual void OnCursorChanged(EventArgs e) {
            Contract.Requires(e != null);
            EventHandler eh = Events[EventCursor] as EventHandler;
            if (eh != null) {
                 eh(this, e);
            }
 
            ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection);
            if (controlsCollection != null) {
                // PERFNOTE: This is more efficient than using Foreach.  Foreach
                // forces the creation of an array subset enum each time we
                // enumerate
                for(int i = 0; i < controlsCollection.Count; i++) {
                    controlsCollection[i].OnParentCursorChanged(e);
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.OnDockChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual void OnDockChanged(EventArgs e) {
            Contract.Requires(e != null);
            EventHandler eh = Events[EventDock] as EventHandler;
            if (eh != null) {
                 eh(this, e);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.OnEnabledChanged"]/*' />
        /// <devdoc>
        /// <para>Raises the <see cref='System.Windows.Forms.Control.Enabled'/> event.</para>
        /// <para>Inheriting classes should override this method to handle this event.
        ///    Call base.OnEnabled to send this event to any registered event listeners.</para>
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual void OnEnabledChanged(EventArgs e) {
            Contract.Requires(e != null);
            if (GetAnyDisposingInHierarchy()) {
                return;
            }
 
            if (IsHandleCreated) {
                SafeNativeMethods.EnableWindow(new HandleRef(this, Handle), Enabled);
 
                // User-paint controls should repaint when their enabled state changes
                //
                if (GetStyle(ControlStyles.UserPaint)) {
                    Invalidate();
                    Update();
                }
            }
 
            EventHandler eh = Events[EventEnabled] as EventHandler;
            if (eh != null) {
                eh(this, e);
            }
 
            ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection);
            if (controlsCollection != null) {
                // PERFNOTE: This is more efficient than using Foreach.  Foreach
                // forces the creation of an array subset enum each time we
                // enumerate
                for(int i = 0; i < controlsCollection.Count; i++) {
                    controlsCollection[i].OnParentEnabledChanged(e);
                }
            }
        }
 
        // Refer VsWhidbey : 515910 & 269769
        internal virtual void OnFrameWindowActivate(bool fActivate) {
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.OnFontChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual void OnFontChanged(EventArgs e) {
            Contract.Requires(e != null);
            // bail if disposing
            //
            if (GetAnyDisposingInHierarchy()) {
                return;
            }
 
            Invalidate();
 
            if (Properties.ContainsInteger(PropFontHeight)) {
                Properties.SetInteger(PropFontHeight, -1);
            }
 
 
            // Cleanup any font handle wrapper...
            //
            DisposeFontHandle();
 
            if (IsHandleCreated && !GetStyle(ControlStyles.UserPaint)) {
                SetWindowFont();
            }
 
            EventHandler eh = Events[EventFont] as EventHandler;
            if (eh != null) {
                 eh(this, e);
            }
 
            ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection);
            using(new LayoutTransaction(this, this, PropertyNames.Font, false)) {
                if (controlsCollection != null) {
                    // This may have changed the sizes of our children.
                    // PERFNOTE: This is more efficient than using Foreach.  Foreach
                    // forces the creation of an array subset enum each time we
                    // enumerate
                    for(int i = 0; i < controlsCollection.Count; i++) {
                        controlsCollection[i].OnParentFontChanged(e);
                    }
                }
            }
 
            LayoutTransaction.DoLayout(this,this,PropertyNames.Font);            
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.OnForeColorChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual void OnForeColorChanged(EventArgs e) {
            Contract.Requires(e != null);
            if (GetAnyDisposingInHierarchy()) {
                return;
            }
 
            Invalidate();
 
            EventHandler eh = Events[EventForeColor] as EventHandler;
            if (eh != null) {
                 eh(this, e);
            }
 
            ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection);
            if (controlsCollection != null) {
                // PERFNOTE: This is more efficient than using Foreach.  Foreach
                // forces the creation of an array subset enum each time we
                // enumerate
                for(int i = 0; i < controlsCollection.Count; i++) {
                    controlsCollection[i].OnParentForeColorChanged(e);
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.OnRightToLeftChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual void OnRightToLeftChanged(EventArgs e) {
            Contract.Requires(e != null);
            if (GetAnyDisposingInHierarchy()) {
                return;
            }
            
            // update the scroll position when the handle has been created
            // MUST SET THIS BEFORE CALLING RecreateHandle!!!
            SetState2(STATE2_SETSCROLLPOS, true);
 
            RecreateHandle();
 
            EventHandler eh = Events[EventRightToLeft] as EventHandler;
            if (eh != null) {
                 eh(this, e);
            }
 
            ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection);
            if (controlsCollection != null) {
                // PERFNOTE: This is more efficient than using Foreach.  Foreach
                // forces the creation of an array subset enum each time we
                // enumerate
                for(int i = 0; i < controlsCollection.Count; i++) {
                    controlsCollection[i].OnParentRightToLeftChanged(e);
                }
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.OnNotifyMessage"]/*' />
        /// <devdoc>
        ///    OnNotifyMessage is called if the ControlStyles.EnableNotifyMessage
        ///    bit is set. This allows for semi-trusted controls to listen to
        ///    window messages, without allowing them to actually modify the
        ///    message.
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual void OnNotifyMessage(Message m) {
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.OnParentBackColorChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual void OnParentBackColorChanged(EventArgs e) {
            Contract.Requires(e != null);
            Color backColor = Properties.GetColor(PropBackColor);
            if (backColor.IsEmpty) {
                OnBackColorChanged(e);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.OnParentBackgroundImageChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual void OnParentBackgroundImageChanged(EventArgs e) {
            Contract.Requires(e != null);
            OnBackgroundImageChanged(e);
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.OnParentBindingContextChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual void OnParentBindingContextChanged(EventArgs e) {
            Contract.Requires(e != null);
            if (Properties.GetObject(PropBindingManager) == null) {
                OnBindingContextChanged(e);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.OnParentCursorChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual void OnParentCursorChanged(EventArgs e) {
            Contract.Requires(e != null);
            if (Properties.GetObject(PropCursor) == null) {
                OnCursorChanged(e);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.OnParentEnabledChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual void OnParentEnabledChanged(EventArgs e) {
            Contract.Requires(e != null);
            if (GetState(STATE_ENABLED)) {
                OnEnabledChanged(e);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.OnParentFontChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual void OnParentFontChanged(EventArgs e) {
            Contract.Requires(e != null);
            if (Properties.GetObject(PropFont) == null) {
                OnFontChanged(e);
            }
        }
 
 
        // occurs when the parent of this control has recreated
        // its handle.
        // presently internal as we feel this will be rare to
        // require override
        internal virtual void OnParentHandleRecreated() {
            // restore ourselves over to the original control.
 
            // use SetParent directly so as to not raise ParentChanged events
            Control parent = ParentInternal;
            if (parent != null) {
                if (IsHandleCreated) {
                    UnsafeNativeMethods.SetParent(new HandleRef(this, this.Handle), new HandleRef(parent, parent.Handle));
                    UpdateZOrder();
                }
            }
            SetState(STATE_PARENTRECREATING, false);
 
            // if our parent was initially the the parent who's handle just got recreated, we need
            // to recreate ourselves so that we get notification.  See UpdateReflectParent for more details.
            if (ReflectParent == ParentInternal)  {
                 RecreateHandle();
            }
 
        }
 
 
        // occurs when the parent of this control is recreating
        // its handle.
        // presently internal as we feel this will be rare to
        // require override
        internal virtual void  OnParentHandleRecreating() {
            SetState(STATE_PARENTRECREATING, true);
            // swoop this control over to the parking window.
 
            // if we left it parented to the parent control, the DestroyWindow
            // would force us to destroy our handle as well... hopefully
            // parenting us over to the parking window and restoring ourselves
            // should help improve recreate perf.
 
            // use SetParent directly so as to not raise ParentChanged events
            if (IsHandleCreated) {
                Application.ParkHandle(new HandleRef(this, this.Handle), this.DpiAwarenessContext);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.OnParentForeColorChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual void OnParentForeColorChanged(EventArgs e) {
            Contract.Requires(e != null);
            Color foreColor = Properties.GetColor(PropForeColor);
            if (foreColor.IsEmpty) {
                OnForeColorChanged(e);
            }
        }
 
        /// <include file='doc\Control.uex' path='docs/doc[@for="Control.OnParentRightToLeftChanged"]/*' />
        /// <devdoc