From af250234c0100bf58c244b231be5f680466d4987 Mon Sep 17 00:00:00 2001 From: Jeremy Kuhne Date: Tue, 24 Sep 2024 10:04:39 -0700 Subject: [PATCH] Update another set of PropertyStore usages (#12209) This actually removes one of the legacy methods, so yay progress. In Form the owned forms set is now a List
rather than a manually managed array. --- .../Forms/ActiveX/Control.ActiveXImpl.cs | 4 +- .../src/System/Windows/Forms/Control.cs | 12 +- .../Windows/Forms/Controls/Labels/Label.cs | 80 ++- .../Forms/Controls/ToolStrips/ToolStrip.cs | 136 ++--- .../Controls/ToolStrips/ToolStripDropDown.cs | 59 +-- .../Controls/ToolStrips/ToolStripItem.cs | 125 ++--- .../Controls/ToolStrips/ToolStripPanel.cs | 7 +- .../Controls/ToolStrips/ToolStripPanelRow.cs | 25 +- .../src/System/Windows/Forms/Form.cs | 473 ++++++------------ .../Layout/Containers/ContainerControl.cs | 13 +- .../Windows/Forms/Layout/DefaultLayout.cs | 81 ++- .../Windows/Forms/Layout/TableLayout.cs | 11 +- .../src/System/Windows/Forms/PropertyStore.cs | 13 +- .../Windows/Forms/ToolStripItemTests.cs | 3 +- 14 files changed, 355 insertions(+), 687 deletions(-) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ActiveX/Control.ActiveXImpl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ActiveX/Control.ActiveXImpl.cs index 87dc77c7577..60cecbb721a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ActiveX/Control.ActiveXImpl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ActiveX/Control.ActiveXImpl.cs @@ -88,12 +88,10 @@ private ActiveXImpl ActiveXInstance throw new NotSupportedException(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 instead of fetching from the property store. SetExtendedState(ExtendedStates.IsActiveX, true); - Properties.AddValue(s_activeXImplProperty, activeXImpl); + activeXImpl = Properties.AddValue(s_activeXImplProperty, new ActiveXImpl(this)); } return activeXImpl; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs index 81f66852e52..5f886c9191d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs @@ -1976,8 +1976,7 @@ internal HFONT FontHandle { if (!Properties.TryGetValue(s_fontHandleWrapperProperty, out FontHandleWrapper? fontHandle)) { - fontHandle = new FontHandleWrapper(font); - Properties.AddValue(s_fontHandleWrapperProperty, fontHandle); + fontHandle = Properties.AddValue(s_fontHandleWrapperProperty, new FontHandleWrapper(font)); } return fontHandle.Handle; @@ -2003,10 +2002,7 @@ internal HFONT FontHandle if (fontHandle is null) { - font = ambientFont; - fontHandle = new FontHandleWrapper(font); - - Properties.AddValue(s_fontHandleWrapperProperty, fontHandle); + fontHandle = Properties.AddValue(s_fontHandleWrapperProperty, new FontHandleWrapper(ambientFont)); } return fontHandle.Handle; @@ -2028,9 +2024,7 @@ protected int FontHeight if (TryGetExplicitlySetFont(out Font? font)) { - fontHeight = font.Height; - Properties.AddValue(s_fontHeightProperty, fontHeight); - return fontHeight; + return Properties.AddValue(s_fontHeightProperty, font.Height); } // Ask the parent if it has the font height. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/Labels/Label.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/Labels/Label.cs index 72742ae815a..666d1cb6fe8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/Labels/Label.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/Labels/Label.cs @@ -369,7 +369,7 @@ public Image? Image { get { - Image? image = (Image?)Properties.GetObject(s_propImage); + Image? image = Properties.GetValueOrDefault(s_propImage); if (image is null && ImageList is not null && ImageIndexer.ActualIndex >= 0) { @@ -382,28 +382,28 @@ public Image? Image } set { - if (Image != value) + if (Image == value) { - StopAnimate(); + return; + } - Properties.SetObject(s_propImage, value); - if (value is not null) - { - ImageIndex = -1; - ImageList = null; - } + StopAnimate(); - // Hook up the frame changed event - // - Animate(); - Invalidate(); + Properties.AddOrRemoveValue(s_propImage, value); + if (value is not null) + { + ImageIndex = -1; + ImageList = null; } + + // Hook up the frame changed event + Animate(); + Invalidate(); } } /// - /// Gets or sets the index value of the images displayed on the - /// . + /// Gets or sets the index value of the images displayed on the . /// [TypeConverter(typeof(ImageIndexConverter))] [Editor($"System.Windows.Forms.Design.ImageIndexEditor, {AssemblyRef.SystemDesign}", typeof(UITypeEditor))] @@ -442,7 +442,7 @@ public int ImageIndex if (value != ImageList.Indexer.DefaultIndex) { // Image.set calls ImageIndex = -1 - Properties.SetObject(s_propImage, null); + Properties.RemoveValue(s_propImage); } ImageIndexer.Index = value; @@ -472,7 +472,7 @@ public string? ImageKey } // Image.set calls ImageIndex = -1 - Properties.SetObject(s_propImage, null); + Properties.RemoveValue(s_propImage); ImageIndexer.Key = value; Invalidate(); @@ -484,7 +484,7 @@ internal LabelImageIndexer ImageIndexer get { // Demand create the ImageIndexer property - if ((!(Properties.GetObject(s_propImageIndex, out bool found) is LabelImageIndexer imageIndexer)) || (!found)) + if (!Properties.TryGetValue(s_propImageIndex, out LabelImageIndexer? imageIndexer)) { imageIndexer = new LabelImageIndexer(this); ImageIndexer = imageIndexer; @@ -492,10 +492,7 @@ internal LabelImageIndexer ImageIndexer return imageIndexer; } - set - { - Properties.SetObject(s_propImageIndex, value); - } + set => Properties.AddOrRemoveValue(s_propImageIndex, value); } /// @@ -507,38 +504,36 @@ internal LabelImageIndexer ImageIndexer [SRCategory(nameof(SR.CatAppearance))] public ImageList? ImageList { - get => (ImageList?)Properties.GetObject(s_propImageList); + get => Properties.GetValueOrDefault(s_propImageList); set { - if (ImageList == value) + ImageList? imageList = ImageList; + + if (imageList == value) { return; } - EventHandler recreateHandler = new(ImageListRecreateHandle); - EventHandler disposedHandler = new(DetachImageList); - // Remove the previous imagelist handle recreate handler - ImageList? imageList = ImageList; if (imageList is not null) { - imageList.RecreateHandle -= recreateHandler; - imageList.Disposed -= disposedHandler; + imageList.RecreateHandle -= ImageListRecreateHandle; + imageList.Disposed -= DetachImageList; } // Make sure we don't have an Image as well as an ImageList if (value is not null) { - Properties.SetObject(s_propImage, null); // Image.set calls ImageList = null + Properties.RemoveValue(s_propImage); } - Properties.SetObject(s_propImageList, value); + Properties.AddOrRemoveValue(s_propImageList, value); // Add the new ImageList handle recreate handler if (value is not null) { - value.RecreateHandle += recreateHandler; - value.Disposed += disposedHandler; + value.RecreateHandle += ImageListRecreateHandle; + value.Disposed += DetachImageList; } Invalidate(); @@ -858,7 +853,7 @@ internal void AdjustSize() private void Animate(bool animate) { bool currentlyAnimating = _labelState[s_stateAnimating] != 0; - if (animate == currentlyAnimating || Properties.GetObject(s_propImage) is not Image image) + if (animate == currentlyAnimating || !Properties.TryGetValue(s_propImage, out Image? image)) { return; } @@ -951,17 +946,14 @@ protected override void Dispose(bool disposing) StopAnimate(); // Holding on to images and image list is a memory leak. - if (ImageList is not null) + if (ImageList is { } imageList) { - ImageList.Disposed -= DetachImageList; - ImageList.RecreateHandle -= ImageListRecreateHandle; - Properties.SetObject(s_propImageList, null); + imageList.Disposed -= DetachImageList; + imageList.RecreateHandle -= ImageListRecreateHandle; + Properties.RemoveValue(s_propImageList); } - if (Image is not null) - { - Properties.SetObject(s_propImage, null); - } + Properties.RemoveValue(s_propImage); _textToolTip?.Dispose(); _textToolTip = null; @@ -1411,7 +1403,7 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound private void ResetImage() => Image = null; - private bool ShouldSerializeImage() => Properties.ContainsObjectThatIsNotNull(s_propImage); + private bool ShouldSerializeImage() => Properties.ContainsKey(s_propImage); internal override void SetToolTip(ToolTip toolTip) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStrip.cs index c29c48eff00..5b9bbe848d6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStrip.cs @@ -381,30 +381,25 @@ public override BindingContext? BindingContext { get { - BindingContext? bc = (BindingContext?)Properties.GetObject(s_propBindingContext); - if (bc is not null) + if (Properties.TryGetValue(s_propBindingContext, out BindingContext? context)) { - return bc; + return context; } - // try the parent - Control? parent = ParentInternal; - if (parent is not null && parent.CanAccessProperties) + // Try the parent. + if (ParentInternal is { } parent && parent.CanAccessProperties) { return parent.BindingContext; } - // we don't have a binding context + // We don't have a binding context. return null; } - set { - if (Properties.GetObject(s_propBindingContext) != value) + if (Properties.AddOrRemoveValue(s_propBindingContext, value) != value) { - Properties.SetObject(s_propBindingContext, value); - - // re-wire the bindings + // Re-wire the bindings. OnBindingContextChanged(EventArgs.Empty); } } @@ -415,10 +410,7 @@ public override BindingContext? BindingContext [SRCategory(nameof(SR.CatLayout))] public bool CanOverflow { - get - { - return GetToolStripState(STATE_CANOVERFLOW); - } + get => GetToolStripState(STATE_CANOVERFLOW); set { if (GetToolStripState(STATE_CANOVERFLOW) != value) @@ -1426,25 +1418,11 @@ public event PaintEventHandler? PaintGrip remove => Events.RemoveHandler(s_eventPaintGrip, value); } - internal RestoreFocusMessageFilter RestoreFocusFilter - { - get - { - _restoreFocusFilter ??= new RestoreFocusMessageFilter(this); + internal RestoreFocusMessageFilter RestoreFocusFilter => _restoreFocusFilter ??= new RestoreFocusMessageFilter(this); - return _restoreFocusFilter; - } - } + internal ToolStripPanelCell? ToolStripPanelCell => ((ISupportToolStripPanel)this).ToolStripPanelCell; - internal ToolStripPanelCell? ToolStripPanelCell - { - get { return ((ISupportToolStripPanel)this).ToolStripPanelCell; } - } - - internal ToolStripPanelRow? ToolStripPanelRow - { - get { return ((ISupportToolStripPanel)this).ToolStripPanelRow; } - } + internal ToolStripPanelRow? ToolStripPanelRow => ((ISupportToolStripPanel)this).ToolStripPanelRow; // fetches the Cell associated with this toolstrip. ToolStripPanelCell? ISupportToolStripPanel.ToolStripPanelCell @@ -1452,13 +1430,9 @@ internal ToolStripPanelRow? ToolStripPanelRow get { ToolStripPanelCell? toolStripPanelCell = null; - if (!IsDropDown && !IsDisposed) + if (!IsDropDown && !IsDisposed && !Properties.TryGetValue(s_propToolStripPanelCell, out toolStripPanelCell)) { - if (!Properties.TryGetObject(s_propToolStripPanelCell, out toolStripPanelCell)) - { - toolStripPanelCell = new ToolStripPanelCell(this); - Properties.SetObject(s_propToolStripPanelCell, toolStripPanelCell); - } + toolStripPanelCell = Properties.AddValue(s_propToolStripPanelCell, new ToolStripPanelCell(this)); } return toolStripPanelCell; @@ -1467,48 +1441,47 @@ internal ToolStripPanelRow? ToolStripPanelRow ToolStripPanelRow? ISupportToolStripPanel.ToolStripPanelRow { - get - { - return ToolStripPanelCell?.ToolStripPanelRow; - } + get => ToolStripPanelCell?.ToolStripPanelRow; set { ToolStripPanelRow? oldToolStripPanelRow = ToolStripPanelRow; - if (oldToolStripPanelRow != value) + if (oldToolStripPanelRow == value) { - ToolStripPanelCell? cell = ToolStripPanelCell; - if (cell is null) - { - return; - } + return; + } + + ToolStripPanelCell? cell = ToolStripPanelCell; + if (cell is null) + { + return; + } - cell.ToolStripPanelRow = value; + cell.ToolStripPanelRow = value; - if (value is not null) + if (value is not null) + { + if (oldToolStripPanelRow is null || oldToolStripPanelRow.Orientation != value.Orientation) { - if (oldToolStripPanelRow is null || oldToolStripPanelRow.Orientation != value.Orientation) + if (_layoutStyle == ToolStripLayoutStyle.StackWithOverflow) { - if (_layoutStyle == ToolStripLayoutStyle.StackWithOverflow) - { - UpdateLayoutStyle(value.Orientation); - } - else - { - UpdateOrientation(value.Orientation); - } + UpdateLayoutStyle(value.Orientation); } - } - else - { - if (oldToolStripPanelRow is not null && oldToolStripPanelRow.ControlsInternal.Contains(this)) + else { - oldToolStripPanelRow.ControlsInternal.Remove(this); + UpdateOrientation(value.Orientation); } - - UpdateLayoutStyle(Dock); } } + else + { + if (oldToolStripPanelRow is not null && oldToolStripPanelRow.ControlsInternal.Contains(this)) + { + oldToolStripPanelRow.ControlsInternal.Remove(this); + } + + UpdateLayoutStyle(Dock); + } } } @@ -1738,10 +1711,9 @@ internal ToolTip ToolTip { get { - if (!Properties.TryGetObject(s_propToolTip, out ToolTip? toolTip) || toolTip is null) + if (!Properties.TryGetValue(s_propToolTip, out ToolTip? toolTip)) { - toolTip = new ToolTip(); - Properties.SetObject(s_propToolTip, toolTip); + toolTip = Properties.AddValue(s_propToolTip, new ToolTip()); } return toolTip; @@ -1970,27 +1942,31 @@ protected override void Dispose(bool disposing) SuspendLayout(); overflow?.SuspendLayout(); - // if there's a problem in config, don't be a leaker. + // If there's a problem in config, don't be a leaker. SetToolStripState(STATE_DISPOSINGITEMS, true); _lastMouseDownedItem = null; - HookStaticEvents(/*hook=*/false); + HookStaticEvents(hook: false); - if (Properties.GetObject(s_propToolStripPanelCell) is ToolStripPanelCell toolStripPanelCell) + if (Properties.TryGetValue(s_propToolStripPanelCell, out ToolStripPanelCell? toolStripPanelCell)) { toolStripPanelCell.Dispose(); + Properties.RemoveValue(s_propToolStripPanelCell); } _cachedItemHdcInfo?.Dispose(); _mouseHoverTimer?.Dispose(); - ToolTip? toolTip = (ToolTip?)Properties.GetObject(s_propToolTip); - toolTip?.Dispose(); + if (Properties.TryGetValue(s_propToolTip, out ToolTip? toolTip)) + { + toolTip?.Dispose(); + Properties.RemoveValue(s_propToolTip); + } if (!Items.IsReadOnly) { - // only dispose the items we actually own. + // Only dispose the items we actually own. for (int i = Items.Count - 1; i >= 0; i--) { Items[i].Dispose(); @@ -1999,21 +1975,19 @@ protected override void Dispose(bool disposing) Items.Clear(); } - // clean up items not in the Items list + // Clean up items not in the Items list. _toolStripGrip?.Dispose(); _toolStripOverflowButton?.Dispose(); - // remove the restore focus filter + // Remove the restore focus filter. if (_restoreFocusFilter is not null) { - // PERF, - Application.ThreadContext.FromCurrent().RemoveMessageFilter(_restoreFocusFilter); _restoreFocusFilter = null; } - // exit menu mode if necessary. + // Exit menu mode if necessary. bool exitMenuMode = false; if (ToolStripManager.ModalMenuFilter.GetActiveToolStrip() == this) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripDropDown.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripDropDown.cs index c1427d2e01e..378aad339dd 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripDropDown.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripDropDown.cs @@ -4,7 +4,6 @@ using System.Collections.Specialized; using System.ComponentModel; using System.Drawing; -using System.Globalization; using System.Windows.Forms.Layout; namespace System.Windows.Forms; @@ -82,11 +81,8 @@ public bool AllowTransparency if (!value) { - if (Properties.ContainsKey(s_propOpacity)) - { - Properties.AddValue(s_propOpacity, 1.0f); - } - + // This sets it back to default, which is 1.0d. + Properties.RemoveValue(s_propOpacity); UpdateLayered(); } } @@ -618,30 +614,14 @@ protected internal override Size MaxItemSize [EditorBrowsable(EditorBrowsableState.Advanced)] public double Opacity { - get - { - object? opacity = Properties.GetObject(s_propOpacity); - if (opacity is not null) - { - return Convert.ToDouble(opacity, CultureInfo.InvariantCulture); - } - - return 1.0f; - } + get => Properties.GetValueOrDefault(s_propOpacity, 1.0d); set { - if (value > 1.0) - { - value = 1.0f; - } - else if (value < 0.0) - { - value = 0.0f; - } + value = Math.Clamp(value, 0.0d, 1.0d); - Properties.SetObject(s_propOpacity, value); + Properties.AddOrRemoveValue(s_propOpacity, value, 1.0d); - bool oldLayered = (_state[s_stateLayered]); + bool oldLayered = _state[s_stateLayered]; if (OpacityAsByte < 255) { AllowTransparency = true; @@ -652,7 +632,7 @@ public double Opacity _state[s_stateLayered] = false; } - if (oldLayered != (_state[s_stateLayered])) + if (oldLayered != _state[s_stateLayered]) { UpdateStyles(); } @@ -661,26 +641,17 @@ public double Opacity } } - private byte OpacityAsByte - { - get - { - return (byte)(Opacity * 255.0f); - } - } + private byte OpacityAsByte => (byte)(Opacity * 255.0f); [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] - public new ToolStripOverflowButton OverflowButton - { - get => base.OverflowButton; - } + public new ToolStripOverflowButton OverflowButton => base.OverflowButton; [DefaultValue(null)] [Browsable(false)] public ToolStripItem? OwnerItem { - get { return _ownerItem; } + get => _ownerItem; set { if (_ownerItem != value) @@ -828,14 +799,8 @@ private bool RightToLeftInherited internal Control? SourceControlInternal { - get - { - return Properties.GetObject(s_propSourceControl) as Control; - } - set - { - Properties.SetObject(s_propSourceControl, value); - } + get => Properties.GetValueOrDefault(s_propSourceControl); + set => Properties.AddOrRemoveValue(s_propSourceControl, value); } internal override SHOW_WINDOW_CMD ShowParams => SHOW_WINDOW_CMD.SW_SHOWNOACTIVATE; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripItem.cs index 343e2509c9d..bc02f91a00f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripItem.cs @@ -179,7 +179,7 @@ protected ToolStripItem(string? text, Image? image, EventHandler? onClick, strin /// /// Indicates whether or not this control has an accessible object associated with it. /// - internal bool IsAccessibilityObjectCreated => Properties.GetObject(s_accessibilityProperty) is AccessibleObject; + internal bool IsAccessibilityObjectCreated => Properties.ContainsKey(s_accessibilityProperty); /// /// The Accessibility Object for this Control @@ -192,11 +192,9 @@ public AccessibleObject AccessibilityObject { get { - AccessibleObject? accessibleObject = (AccessibleObject?)Properties.GetObject(s_accessibilityProperty); - if (accessibleObject is null) + if (!Properties.TryGetValue(s_accessibilityProperty, out AccessibleObject? accessibleObject)) { - accessibleObject = CreateAccessibilityInstance(); - Properties.SetObject(s_accessibilityProperty, accessibleObject); + accessibleObject = Properties.AddValue(s_accessibilityProperty, CreateAccessibilityInstance()); } return accessibleObject; @@ -213,10 +211,10 @@ public AccessibleObject AccessibilityObject [SRDescription(nameof(SR.ToolStripItemAccessibleDefaultActionDescr))] public string? AccessibleDefaultActionDescription { - get => (string?)Properties.GetObject(s_accessibleDefaultActionDescriptionProperty); + get => Properties.GetValueOrDefault(s_accessibleDefaultActionDescriptionProperty); set { - Properties.SetObject(s_accessibleDefaultActionDescriptionProperty, value); + Properties.AddOrRemoveValue(s_accessibleDefaultActionDescriptionProperty, value); OnAccessibleDefaultActionDescriptionChanged(EventArgs.Empty); } } @@ -230,10 +228,10 @@ public string? AccessibleDefaultActionDescription [SRDescription(nameof(SR.ToolStripItemAccessibleDescriptionDescr))] public string? AccessibleDescription { - get => (string?)Properties.GetObject(s_accessibleDescriptionProperty); + get => Properties.GetValueOrDefault(s_accessibleDescriptionProperty); set { - Properties.SetObject(s_accessibleDescriptionProperty, value); + Properties.AddOrRemoveValue(s_accessibleDescriptionProperty, value); OnAccessibleDescriptionChanged(EventArgs.Empty); } } @@ -247,10 +245,10 @@ public string? AccessibleDescription [SRDescription(nameof(SR.ToolStripItemAccessibleNameDescr))] public string? AccessibleName { - get => (string?)Properties.GetObject(s_accessibleNameProperty); + get => Properties.GetValueOrDefault(s_accessibleNameProperty); set { - Properties.SetObject(s_accessibleNameProperty, value); + Properties.AddOrRemoveValue(s_accessibleNameProperty, value); OnAccessibleNameChanged(EventArgs.Empty); } } @@ -389,12 +387,11 @@ public event EventHandler? AvailableChanged [DefaultValue(null)] public virtual Image? BackgroundImage { - get => Properties.GetObject(s_backgroundImageProperty) as Image; + get => Properties.GetValueOrDefault(s_backgroundImageProperty); set { - if (BackgroundImage != value) + if (Properties.AddOrRemoveValue(s_backgroundImageProperty, value) != value) { - Properties.SetObject(s_backgroundImageProperty, value); Invalidate(); } } @@ -927,10 +924,8 @@ public virtual Font Font } set { - var local = (Font?)Properties.GetObject(s_fontProperty); - if (local != value) + if (Properties.AddOrRemoveValue(s_fontProperty, value) != value) { - Properties.SetObject(s_fontProperty, value); OnFontChanged(EventArgs.Empty); } } @@ -947,7 +942,7 @@ public event GiveFeedbackEventHandler? GiveFeedback } /// - /// The height of this control + /// The height of this control. /// [SRCategory(nameof(SR.CatLayout))] [Browsable(false)] @@ -1031,7 +1026,7 @@ public virtual Image? Image { get { - Image? image = (Image?)Properties.GetObject(s_imageProperty); + Image? image = Properties.GetValueOrDefault(s_imageProperty); if (image is null && Owner?.ImageList is not null && ImageIndexer.ActualIndex >= 0) { bool disposing = _state[s_stateDisposing]; @@ -1040,7 +1035,7 @@ public virtual Image? Image // CACHE (by design). If we fetched out of the image list every time it would dramatically hit perf. image = Owner.ImageList.Images[ImageIndexer.ActualIndex]; _state[s_stateInvalidMirroredImage] = true; - Properties.SetObject(s_imageProperty, image); + Properties.AddValue(s_imageProperty, image); return image; } @@ -1073,7 +1068,7 @@ public virtual Image? Image ImageIndex = ImageList.Indexer.DefaultIndex; } - Properties.SetObject(s_imageProperty, value); + Properties.AddOrRemoveValue(s_imageProperty, value); _state[s_stateInvalidMirroredImage] = true; Animate(); @@ -1089,19 +1084,21 @@ public Color ImageTransparentColor get => _imageTransparentColor; set { - if (_imageTransparentColor != value) + if (_imageTransparentColor == value) { - _imageTransparentColor = value; - if (Image is Bitmap currentImage && value != Color.Empty) + return; + } + + _imageTransparentColor = value; + if (Image is Bitmap currentImage && value != Color.Empty) + { + if (currentImage.RawFormat.Guid != ImageFormat.Icon.Guid && !ImageAnimator.CanAnimate(currentImage)) { - if (currentImage.RawFormat.Guid != ImageFormat.Icon.Guid && !ImageAnimator.CanAnimate(currentImage)) - { - currentImage.MakeTransparent(_imageTransparentColor); - } + currentImage.MakeTransparent(_imageTransparentColor); } - - Invalidate(); } + + Invalidate(); } } @@ -1137,7 +1134,7 @@ public int ImageIndex _state[s_stateInvalidMirroredImage] = true; // Set the Image Property to null - Properties.SetObject(s_imageProperty, null); + Properties.RemoveValue(s_imageProperty); InvalidateItemLayout(PropertyNames.ImageIndex); } @@ -1166,8 +1163,7 @@ public string ImageKey { ImageIndexer.Key = value; _state[s_stateInvalidMirroredImage] = true; - Properties.SetObject(s_imageProperty, null); - + Properties.RemoveValue(s_imageProperty); InvalidateItemLayout(PropertyNames.ImageKey); } } @@ -1391,7 +1387,7 @@ public event MouseEventHandler? MouseUp [DefaultValue(null)] public string? Name { - get => WindowsFormsUtils.GetComponentName(this, (string?)Properties.GetObject(s_nameProperty)); + get => WindowsFormsUtils.GetComponentName(this, Properties.GetValueOrDefault(s_nameProperty)); set { if (DesignMode) @@ -1399,7 +1395,7 @@ public string? Name return; } - Properties.SetObject(s_nameProperty, value); + Properties.AddOrRemoveValue(s_nameProperty, value); } } @@ -1561,7 +1557,7 @@ internal Size PreferredImageSize return Size.Empty; } - Image? image = (Image?)Properties.GetObject(s_imageProperty); + Image? image = Properties.GetValueOrDefault(s_imageProperty); bool usingImageList = ((Owner is not null) && (Owner.ImageList is not null) && (ImageIndexer.ActualIndex >= 0)); if (ImageScaling == ToolStripItemImageScaling.SizeToFit) @@ -1733,12 +1729,12 @@ internal Image? MirroredImage Image mirroredImage = (Image)image.Clone(); mirroredImage.RotateFlip(RotateFlipType.RotateNoneFlipX); - Properties.SetObject(s_mirroredImageProperty, mirroredImage); + Properties.AddValue(s_mirroredImageProperty, mirroredImage); _state[s_stateInvalidMirroredImage] = false; return mirroredImage; } - return Properties.GetObject(s_mirroredImageProperty) as Image; + return Properties.GetValueOrDefault(s_mirroredImageProperty); } } @@ -2095,15 +2091,13 @@ internal bool BeginDragForItemReorder() /// should not call base.CreateAccessibilityObject. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual AccessibleObject CreateAccessibilityInstance() - => new ToolStripItemAccessibleObject(this); + protected virtual AccessibleObject CreateAccessibilityInstance() => new ToolStripItemAccessibleObject(this); /// /// Creates an instance of the object that defines how image and text /// gets laid out in the ToolStripItem /// - private protected virtual ToolStripItemInternalLayout CreateInternalLayout() - => new(this); + private protected virtual ToolStripItemInternalLayout CreateInternalLayout() => new(this); /// /// Disposes this ToolStrip item. @@ -2130,8 +2124,8 @@ protected override void Dispose(bool disposing) { // need to call base() first since the Component.Dispose(_) is listened to by the ComponentChangeService // which Serializes the object in Undo-Redo transactions. - Properties.SetObject(s_mirroredImageProperty, null); - Properties.SetObject(s_imageProperty, null); + Properties.RemoveValue(s_mirroredImageProperty); + Properties.RemoveValue(s_imageProperty); _state[s_stateDisposing] = false; } } @@ -2414,10 +2408,10 @@ internal void InvalidateItemLayout(string affectedProperty) internal void InvalidateImageListImage() { - // invalidate the cache. + // Invalidate the cache. if (ImageIndexer.ActualIndex >= 0) { - Properties.SetObject(s_imageProperty, null); + Properties.RemoveValue(s_imageProperty); InvalidateItemLayout(PropertyNames.Image); } } @@ -3096,39 +3090,27 @@ protected internal virtual bool ProcessMnemonic(char charCode) return true; } - internal void RaiseCancelEvent(object key, CancelEventArgs e) - => ((CancelEventHandler?)Events[key])?.Invoke(this, e); + internal void RaiseCancelEvent(object key, CancelEventArgs e) => ((CancelEventHandler?)Events[key])?.Invoke(this, e); - internal void RaiseDragEvent(object key, DragEventArgs e) - => ((DragEventHandler?)Events[key])?.Invoke(this, e); + internal void RaiseDragEvent(object key, DragEventArgs e) => ((DragEventHandler?)Events[key])?.Invoke(this, e); - internal void RaiseKeyEvent(object key, KeyEventArgs e) - => ((KeyEventHandler?)Events[key])?.Invoke(this, e); + internal void RaiseKeyEvent(object key, KeyEventArgs e) => ((KeyEventHandler?)Events[key])?.Invoke(this, e); - internal void RaiseKeyPressEvent(object key, KeyPressEventArgs e) - => ((KeyPressEventHandler?)Events[key])?.Invoke(this, e); + internal void RaiseKeyPressEvent(object key, KeyPressEventArgs e) => ((KeyPressEventHandler?)Events[key])?.Invoke(this, e); - internal void RaiseMouseEvent(object key, MouseEventArgs e) - => ((MouseEventHandler?)Events[key])?.Invoke(this, e); + internal void RaiseMouseEvent(object key, MouseEventArgs e) => ((MouseEventHandler?)Events[key])?.Invoke(this, e); - internal void RaisePaintEvent(object key, PaintEventArgs e) - => ((PaintEventHandler?)Events[key])?.Invoke(this, e); + internal void RaisePaintEvent(object key, PaintEventArgs e) => ((PaintEventHandler?)Events[key])?.Invoke(this, e); - internal void RaiseQueryContinueDragEvent(object key, QueryContinueDragEventArgs e) - => ((QueryContinueDragEventHandler?)Events[key])?.Invoke(this, e); + internal void RaiseQueryContinueDragEvent(object key, QueryContinueDragEventArgs e) => + ((QueryContinueDragEventHandler?)Events[key])?.Invoke(this, e); internal virtual void ReleaseUiaProvider() { - if (TryGetAccessibilityObject(out AccessibleObject? accessibleObject)) + if (Properties.TryGetValue(s_accessibilityProperty, out AccessibleObject? accessibleObject)) { PInvoke.UiaDisconnectProvider(accessibleObject, skipOSCheck: true); - Properties.SetObject(s_accessibilityProperty, null); - } - - bool TryGetAccessibilityObject(out AccessibleObject? accessibleObject) - { - accessibleObject = Properties.GetObject(s_accessibilityProperty) as AccessibleObject; - return accessibleObject is not null; + Properties.RemoveValue(s_accessibilityProperty); } } @@ -3679,10 +3661,5 @@ internal virtual void OnKeyboardToolTipUnhook(ToolTip toolTip) /// /// Query font from property bag. /// - internal bool TryGetExplicitlySetFont([NotNullWhen(true)] out Font? local) - { - local = (Font?)Properties.GetObject(s_fontProperty); - - return local is not null; - } + internal bool TryGetExplicitlySetFont([NotNullWhen(true)] out Font? local) => Properties.TryGetValue(s_fontProperty, out local); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripPanel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripPanel.cs index f9023915616..ffa7dc11b69 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripPanel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripPanel.cs @@ -271,12 +271,9 @@ internal ToolStripPanelRowCollection RowsInternal { get { - ToolStripPanelRowCollection? rowCollection = (ToolStripPanelRowCollection?)Properties.GetObject(s_propToolStripPanelRowCollection); - - if (rowCollection is null) + if (!Properties.TryGetValue(s_propToolStripPanelRowCollection, out ToolStripPanelRowCollection? rowCollection)) { - rowCollection = CreateToolStripPanelRowCollection(); - Properties.SetObject(s_propToolStripPanelRowCollection, rowCollection); + rowCollection = Properties.AddValue(s_propToolStripPanelRowCollection, CreateToolStripPanelRowCollection()); } return rowCollection; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripPanelRow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripPanelRow.cs index dea808b50e4..6a7fad46e0b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripPanelRow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripPanelRow.cs @@ -89,36 +89,21 @@ internal ToolStripPanelRowControlCollection ControlsInternal { get { - ToolStripPanelRowControlCollection? controlsCollection = (ToolStripPanelRowControlCollection?)Properties.GetObject(s_propControlsCollection); - - if (controlsCollection is null) + if (!Properties.TryGetValue(s_propControlsCollection, out ToolStripPanelRowControlCollection? controlsCollection)) { - controlsCollection = CreateControlsInstance(); - Properties.SetObject(s_propControlsCollection, controlsCollection); + controlsCollection = Properties.AddValue(s_propControlsCollection, CreateControlsInstance()); } return controlsCollection; } } - internal ArrangedElementCollection Cells - { - get - { - return ControlsInternal.Cells; - } - } + internal ArrangedElementCollection Cells => ControlsInternal.Cells; internal bool CachedBoundsMode { - get - { - return _state[s_stateCachedBoundsMode]; - } - set - { - _state[s_stateCachedBoundsMode] = value; - } + get => _state[s_stateCachedBoundsMode]; + set => _state[s_stateCachedBoundsMode] = value; } private ToolStripPanelRowManager RowManager diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Form.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Form.cs index 45a3d2b55c2..e4f4bdabf17 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Form.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Form.cs @@ -5,7 +5,6 @@ using System.ComponentModel; using System.ComponentModel.Design; using System.Drawing; -using System.Globalization; using System.Runtime.InteropServices; using System.Windows.Forms.Analyzers.Diagnostics; using System.Windows.Forms.Layout; @@ -117,7 +116,6 @@ public partial class Form : ContainerControl private static readonly int s_propOwner = PropertyStore.CreateKey(); private static readonly int s_propOwnedForms = PropertyStore.CreateKey(); private static readonly int s_propMaximizedBounds = PropertyStore.CreateKey(); - private static readonly int s_propOwnedFormsCount = PropertyStore.CreateKey(); private static readonly int s_propMinTrackSize = PropertyStore.CreateKey(); private static readonly int s_propMaxTrackSize = PropertyStore.CreateKey(); @@ -221,15 +219,11 @@ public Form() : base() [SRDescription(nameof(SR.FormAcceptButtonDescr))] public IButtonControl? AcceptButton { - get - { - return (IButtonControl?)Properties.GetObject(s_propAcceptButton); - } + get => Properties.GetValueOrDefault(s_propAcceptButton); set { - if (AcceptButton != value) + if (Properties.AddOrRemoveValue(s_propAcceptButton, value) != value) { - Properties.SetObject(s_propAcceptButton, value); UpdateDefaultButton(); } } @@ -252,41 +246,43 @@ internal bool Active } set { - if ((_formState[s_formStateIsActive] != 0) != value) + if (_formState[s_formStateIsActive] != 0 == value) { - if (value) + return; + } + + if (value) + { + if (!CanRecreateHandle()) { - if (!CanRecreateHandle()) - { - return; - } + return; } + } - _formState[s_formStateIsActive] = value ? 1 : 0; + _formState[s_formStateIsActive] = value ? 1 : 0; - if (value) - { - _formState[s_formStateIsWindowActivated] = 1; + if (value) + { + _formState[s_formStateIsWindowActivated] = 1; - // Check if validation has been canceled to avoid raising Validation event multiple times. - if (!ValidationCancelled) + // Check if validation has been canceled to avoid raising Validation event multiple times. + if (!ValidationCancelled) + { + if (ActiveControl is null) { - if (ActiveControl is null) - { - // If no control is selected focus will go to form - SelectNextControl(null, true, true, true, false); - } - - InnerMostActiveContainerControl.FocusActiveControlInternal(); + // If no control is selected focus will go to form + SelectNextControl(null, true, true, true, false); } - OnActivated(EventArgs.Empty); - } - else - { - _formState[s_formStateIsWindowActivated] = 0; - OnDeactivate(EventArgs.Empty); + InnerMostActiveContainerControl.FocusActiveControlInternal(); } + + OnActivated(EventArgs.Empty); + } + else + { + _formState[s_formStateIsWindowActivated] = 0; + OnDeactivate(EventArgs.Empty); } } } @@ -341,70 +337,50 @@ public Form? ActiveMdiChild /// internal Form? ActiveMdiChildInternal { - get - { - return (Form?)Properties.GetObject(s_propActiveMdiChild); - } - - set - { - Properties.SetObject(s_propActiveMdiChild, value); - } + get => Properties.GetValueOrDefault(s_propActiveMdiChild); + set => Properties.AddOrRemoveValue(s_propActiveMdiChild, value); } // we don't repaint the mdi child that used to be active any more. We used to do this in Activated, but no // longer do because of added event Deactivate. private Form? FormerlyActiveMdiChild { - get - { - return (Form?)Properties.GetObject(s_propFormerlyActiveMdiChild); - } - - set - { - Properties.SetObject(s_propFormerlyActiveMdiChild, value); - } + get => Properties.GetValueOrDefault(s_propFormerlyActiveMdiChild); + set => Properties.AddOrRemoveValue(s_propFormerlyActiveMdiChild, value); } /// - /// Gets or sets - /// a value indicating whether the opacity of the form can be - /// adjusted. + /// Gets or sets a value indicating whether the opacity of the form can be adjusted. /// [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [SRDescription(nameof(SR.ControlAllowTransparencyDescr))] public bool AllowTransparency { - get - { - return _formState[s_formStateAllowTransparency] != 0; - } + get => _formState[s_formStateAllowTransparency] != 0; set { - if (value != (_formState[s_formStateAllowTransparency] != 0)) + if (value == (_formState[s_formStateAllowTransparency] != 0)) { - _formState[s_formStateAllowTransparency] = (value ? 1 : 0); + return; + } - _formState[s_formStateLayered] = _formState[s_formStateAllowTransparency]; + _formState[s_formStateAllowTransparency] = value ? 1 : 0; - UpdateStyles(); + _formState[s_formStateLayered] = _formState[s_formStateAllowTransparency]; - if (!value) - { - if (Properties.ContainsKey(s_propOpacity)) - { - Properties.AddValue(s_propOpacity, 1.0f); - } + UpdateStyles(); - if (Properties.ContainsKey(s_propTransparencyKey)) - { - Properties.AddValue(s_propTransparencyKey, Color.Empty); - } + if (!value) + { + Properties.RemoveValue(s_propOpacity); - UpdateLayered(); + if (Properties.ContainsKey(s_propTransparencyKey)) + { + Properties.AddValue(s_propTransparencyKey, Color.Empty); } + + UpdateLayered(); } } } @@ -426,7 +402,6 @@ public bool AutoScale { return _formState[s_formStateAutoScaling] != 0; } - set { _formStateEx[s_formStateExSettingAutoScale] = 1; @@ -733,22 +708,16 @@ public FormBorderStyle FormBorderStyle } /// - /// Gets - /// or - /// sets the button control that will be clicked when the - /// user presses the ESC key. + /// Gets or sets the button control that will be clicked when the user presses the ESC key. /// [DefaultValue(null)] [SRDescription(nameof(SR.FormCancelButtonDescr))] public IButtonControl? CancelButton { - get - { - return (IButtonControl?)Properties.GetObject(s_propCancelButton); - } + get => Properties.GetValueOrDefault(s_propCancelButton); set { - Properties.SetObject(s_propCancelButton, value); + Properties.AddOrRemoveValue(s_propCancelButton, value); if (value is not null && value.DialogResult == DialogResult.None) { @@ -803,7 +772,6 @@ protected override CreateParams CreateParams else if (TopLevel) { // It doesn't seem to make sense to allow a top-level form to be disabled - // cp.Style &= ~(int)WINDOW_STYLE.WS_DISABLED; } @@ -812,8 +780,7 @@ protected override CreateParams CreateParams cp.ExStyle |= (int)WINDOW_EX_STYLE.WS_EX_LAYERED; } - IWin32Window? dialogOwner = (IWin32Window?)Properties.GetObject(s_propDialogOwner); - if (dialogOwner is not null) + if (Properties.TryGetValue(s_propDialogOwner, out IWin32Window? dialogOwner)) { cp.Parent = GetSafeHandle(dialogOwner).Handle; } @@ -828,25 +795,19 @@ protected override CreateParams CreateParams } FormBorderStyle borderStyle = FormBorderStyle; - if (!ShowIcon && - (borderStyle == FormBorderStyle.Sizable || - borderStyle == FormBorderStyle.Fixed3D || - borderStyle == FormBorderStyle.FixedSingle)) + if (!ShowIcon && (borderStyle is FormBorderStyle.Sizable or FormBorderStyle.Fixed3D or FormBorderStyle.FixedSingle)) { cp.ExStyle |= (int)WINDOW_EX_STYLE.WS_EX_DLGMODALFRAME; } if (IsMdiChild) { - if (Visible - && (WindowState == FormWindowState.Maximized - || WindowState == FormWindowState.Normal)) + if (Visible && (WindowState is FormWindowState.Maximized or FormWindowState.Normal)) { - Form? formMdiParent = (Form?)Properties.GetObject(s_propFormMdiParent); + Form? formMdiParent = Properties.GetValueOrDefault(s_propFormMdiParent); Form? form = formMdiParent?.ActiveMdiChildInternal; - if (form is not null - && form.WindowState == FormWindowState.Maximized) + if (form is not null && form.WindowState == FormWindowState.Maximized) { cp.Style |= (int)WINDOW_STYLE.WS_MAXIMIZE; _formState[s_formStateWindowState] = (int)FormWindowState.Maximized; @@ -1113,23 +1074,14 @@ private bool IsMaximized [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [SRDescription(nameof(SR.FormIsMDIChildDescr))] [MemberNotNullWhen(true, nameof(MdiParentInternal))] - public bool IsMdiChild - { - get => Properties.ContainsObjectThatIsNotNull(s_propFormMdiParent); - } + public bool IsMdiChild => Properties.ContainsKey(s_propFormMdiParent); // Deactivates active MDI child and temporarily marks it as unfocusable, // so that WM_SETFOCUS sent to MDIClient does not activate that child. (See MdiClient.WndProc). internal bool IsMdiChildFocusable { - get => Properties.TryGetObject(s_propMdiChildFocusable, out bool value) && value; - set - { - if (value != IsMdiChildFocusable) - { - Properties.SetObject(s_propMdiChildFocusable, value); - } - } + get => Properties.GetValueOrDefault(s_propMdiChildFocusable); + set => Properties.AddOrRemoveValue(s_propMdiChildFocusable, value); } /// @@ -1303,7 +1255,6 @@ private void UpdateMaximumSize(Size value, bool updateFormSize = true) public event EventHandler? MaximumSizeChanged { add => Events.AddHandler(s_maximumSizeChangedEvent, value); - remove => Events.RemoveHandler(s_maximumSizeChangedEvent, value); } @@ -1313,13 +1264,10 @@ public event EventHandler? MaximumSizeChanged [TypeConverter(typeof(ReferenceConverter))] public MenuStrip? MainMenuStrip { - get - { - return (MenuStrip?)Properties.GetObject(s_propMainMenuStrip); - } + get => Properties.GetValueOrDefault(s_propMainMenuStrip); set { - Properties.SetObject(s_propMainMenuStrip, value); + Properties.AddOrRemoveValue(s_propMainMenuStrip, value); if (IsHandleCreated) { UpdateMenuHandles(recreateMenu: true); @@ -1534,22 +1482,16 @@ internal MdiClient? MdiClient [SRDescription(nameof(SR.FormMDIParentDescr))] public Form? MdiParent { - get - { - return MdiParentInternal; - } - set - { - MdiParentInternal = value; - } + get => MdiParentInternal; + set => MdiParentInternal = value; } private Form? MdiParentInternal { - get => (Form?)Properties.GetObject(s_propFormMdiParent); + get => Properties.GetValueOrDefault(s_propFormMdiParent); set { - Form? formMdiParent = (Form?)Properties.GetObject(s_propFormMdiParent); + Form? formMdiParent = Properties.GetValueOrDefault(s_propFormMdiParent); if (value == formMdiParent && (value is not null || ParentInternal is null)) { return; @@ -1588,7 +1530,7 @@ private Form? MdiParentInternal // and create the handle here. Dock = DockStyle.None; - Properties.SetObject(s_propFormMdiParent, value); + Properties.AddOrRemoveValue(s_propFormMdiParent, value); SetState(States.TopLevel, false); ParentInternal = value.MdiClient; @@ -1618,14 +1560,14 @@ private Form? MdiParentInternal private MdiWindowListStrip? MdiWindowListStrip { - get { return Properties.GetObject(s_propMdiWindowListStrip) as MdiWindowListStrip; } - set { Properties.SetObject(s_propMdiWindowListStrip, value); } + get => Properties.GetValueOrDefault(s_propMdiWindowListStrip); + set => Properties.AddOrRemoveValue(s_propMdiWindowListStrip, value); } private MdiControlStrip? MdiControlStrip { - get { return Properties.GetObject(s_propMdiControlStrip) as MdiControlStrip; } - set { Properties.SetObject(s_propMdiControlStrip, value); } + get => Properties.GetValueOrDefault(s_propMdiControlStrip); + set => Properties.AddOrRemoveValue(s_propMdiControlStrip, value); } /// @@ -1636,40 +1578,22 @@ private MdiControlStrip? MdiControlStrip [SRDescription(nameof(SR.FormMinimizeBoxDescr))] public bool MinimizeBox { - get - { - return _formState[s_formStateMinimizeBox] != 0; - } + get => _formState[s_formStateMinimizeBox] != 0; set { - if (value) - { - _formState[s_formStateMinimizeBox] = 1; - } - else - { - _formState[s_formStateMinimizeBox] = 0; - } - + _formState[s_formStateMinimizeBox] = value ? 1 : 0; UpdateFormStyles(); } } /// - /// Gets a value indicating whether this form is - /// displayed modally. + /// Gets a value indicating whether this form is displayed modally. /// [SRCategory(nameof(SR.CatWindowStyle))] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [SRDescription(nameof(SR.FormModalDescr))] - public bool Modal - { - get - { - return GetState(States.Modal); - } - } + public bool Modal => GetState(States.Modal); /// /// Determines the opacity of the form. This can only be set on top level controls. @@ -1681,30 +1605,14 @@ public bool Modal [DefaultValue(1.0)] public double Opacity { - get - { - object? opacity = Properties.GetObject(s_propOpacity); - if (opacity is not null) - { - return Convert.ToDouble(opacity, CultureInfo.InvariantCulture); - } - - return 1.0f; - } + get => Properties.GetValueOrDefault(s_propOpacity, 1.0d); set { - if (value > 1.0) - { - value = 1.0f; - } - else if (value < 0.0) - { - value = 0.0f; - } + value = Math.Clamp(value, 0.0d, 1.0d); - Properties.SetObject(s_propOpacity, value); + Properties.AddOrRemoveValue(s_propOpacity, value, defaultValue: 1.0d); - bool oldLayered = (_formState[s_formStateLayered] != 0); + bool oldLayered = _formState[s_formStateLayered] != 0; if (OpacityAsByte < 255) { @@ -1735,13 +1643,7 @@ public double Opacity } } - private byte OpacityAsByte - { - get - { - return (byte)(Opacity * 255.0f); - } - } + private byte OpacityAsByte => (byte)(Opacity * 255.0f); /// /// Gets an array of objects that represent all forms that are owned by this form. @@ -1750,22 +1652,7 @@ private byte OpacityAsByte [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [SRDescription(nameof(SR.FormOwnedFormsDescr))] - public Form[] OwnedForms - { - get - { - Form?[]? ownedForms = (Form?[]?)Properties.GetObject(s_propOwnedForms); - int ownedFormsCount = Properties.GetValueOrDefault(s_propOwnedFormsCount); - - Form[] result = new Form[ownedFormsCount]; - if (ownedFormsCount > 0) - { - Array.Copy(ownedForms!, 0, result, 0, ownedFormsCount); - } - - return result; - } - } + public Form[] OwnedForms => Properties.TryGetValue(s_propOwnedForms, out List? ownedForms) ? ([.. ownedForms]) : ([]); /// /// Gets or sets the form that owns this form. @@ -1776,10 +1663,7 @@ public Form[] OwnedForms [SRDescription(nameof(SR.FormOwnerDescr))] public Form? Owner { - get - { - return OwnerInternal; - } + get => OwnerInternal; set { Form? ownerOld = OwnerInternal; @@ -1808,10 +1692,7 @@ public Form? Owner } } - internal Form? OwnerInternal - { - get => Properties.GetValueOrDefault(s_propOwner); - } + internal Form? OwnerInternal => Properties.GetValueOrDefault(s_propOwner); /// /// Gets or sets the restored bounds of the Form. @@ -2971,8 +2852,7 @@ protected void ActivateMdiChild(Form? form) } /// - /// Adds - /// an owned form to this form. + /// Adds an owned form to this form. /// public void AddOwnedForm(Form? ownedForm) { @@ -2987,39 +2867,24 @@ public void AddOwnedForm(Form? ownedForm) return; } - Form?[]? ownedForms = Properties.GetValueOrDefault(s_propOwnedForms); - int ownedFormsCount = Properties.GetValueOrDefault(s_propOwnedFormsCount); - - // Make sure this isn't already in the list: - for (int i = 0; i < ownedFormsCount; i++) + if (!Properties.TryGetValue(s_propOwnedForms, out List? ownedForms)) { - if (ownedForms![i] == ownedForm) - { - return; - } - } - - if (ownedForms is null) - { - ownedForms = new Form[4]; + ownedForms = []; Properties.AddValue(s_propOwnedForms, ownedForms); } - else if (ownedForms.Length == ownedFormsCount) + + // Make sure this isn't already in the list. + if (ownedForms.Contains(ownedForm)) { - Form[] newOwnedForms = new Form[ownedFormsCount * 2]; - Array.Copy(ownedForms, 0, newOwnedForms, 0, ownedFormsCount); - ownedForms = newOwnedForms; - Properties.AddValue(s_propOwnedForms, ownedForms); + return; } - ownedForms[ownedFormsCount] = ownedForm; - Properties.AddValue(s_propOwnedFormsCount, ownedFormsCount + 1); + ownedForms.Add(ownedForm); } // When shrinking the form (i.e. going from Large Fonts to Small // Fonts) we end up making everything too small due to roundoff, // etc... solution - just don't shrink as much. - // private static float AdjustScale(float scale) { // NOTE : This function is cloned in FormDocumentDesigner... remember to keep @@ -3268,12 +3133,10 @@ private void ApplyClientSize() /// internal override void AssignParent(Control? value) { - // If we are being unparented from the MDI client control, remove - // formMDIParent as well. - Form? formMdiParent = (Form?)Properties.GetObject(s_propFormMdiParent); - if (formMdiParent is not null && formMdiParent.MdiClient != value) + // If we are being unparented from the MDI client control, remove formMDIParent as well. + if (Properties.TryGetValue(s_propFormMdiParent, out Form? formMdiParent) && formMdiParent.MdiClient != value) { - Properties.SetObject(s_propFormMdiParent, null); + Properties.RemoveValue(s_propFormMdiParent); } base.AssignParent(value); @@ -3448,8 +3311,7 @@ internal override void AfterControlRemoved(Control control, Control oldParent) } /// - /// Creates the handle for the Form. If a - /// subclass overrides this function, + /// Creates the handle for the Form. If a subclass overrides this function, /// it must call the base implementation. /// [EditorBrowsable(EditorBrowsableState.Advanced)] @@ -3459,7 +3321,7 @@ protected override void CreateHandle() // updates on the parent while creating the handle. Otherwise if the // child is created maximized, the menu ends up with two sets of // MDI child ornaments. - Form? form = (Form?)Properties.GetObject(s_propFormMdiParent); + Form? form = Properties.GetValueOrDefault(s_propFormMdiParent); form?.SuspendUpdateMenuHandles(); try @@ -3634,25 +3496,10 @@ protected override void Dispose(bool disposing) CalledMakeVisible = false; CalledCreateControl = false; - if (Properties.ContainsKey(s_propAcceptButton)) - { - Properties.RemoveValue(s_propAcceptButton); - } - - if (Properties.ContainsKey(s_propCancelButton)) - { - Properties.RemoveValue(s_propCancelButton); - } - - if (Properties.ContainsKey(s_propDefaultButton)) - { - Properties.RemoveValue(s_propDefaultButton); - } - - if (Properties.ContainsKey(s_propActiveMdiChild)) - { - Properties.RemoveValue(s_propActiveMdiChild); - } + Properties.RemoveValue(s_propAcceptButton); + Properties.RemoveValue(s_propCancelButton); + Properties.RemoveValue(s_propDefaultButton); + Properties.RemoveValue(s_propActiveMdiChild); if (MdiWindowListStrip is not null) { @@ -3680,13 +3527,13 @@ protected override void Dispose(bool disposing) Properties.RemoveValue(s_propDialogOwner); - Form?[]? ownedForms = Properties.GetValueOrDefault(s_propOwnedForms); - int ownedFormsCount = Properties.GetValueOrDefault(s_propOwnedFormsCount); - - for (int i = ownedFormsCount - 1; i >= 0; i--) + if (Properties.TryGetValue(s_propOwnedForms, out List? ownedForms)) { - // it calls remove and removes itself. - ownedForms![i]?.Dispose(); + // It calls remove and removes itself. + for (int i = ownedForms.Count - 1; i >= 0; i--) + { + ownedForms[i].Dispose(); + } } if (_smallIcon is not null) @@ -3847,7 +3694,7 @@ private void FillInCreateParamsStartPosition(CreateParams cp) else { Screen desktop; - IWin32Window? dialogOwner = (IWin32Window?)Properties.GetObject(s_propDialogOwner); + IWin32Window? dialogOwner = Properties.GetValueOrDefault(s_propDialogOwner); if ((OwnerInternal is not null) || (dialogOwner is not null)) { HandleRef ownerHandle = dialogOwner is not null @@ -3862,7 +3709,8 @@ private void FillInCreateParamsStartPosition(CreateParams cp) } Rectangle screenRect = desktop.WorkingArea; - // if, we're maximized, then don't set the x & y coordinates (they're @ (0,0) ) + + // If we're maximized then don't set the x & y coordinates (they're @(0,0)) if (WindowState != FormWindowState.Maximized) { cp.X = Math.Max(screenRect.X, screenRect.X + (screenRect.Width - cp.Width) / 2); @@ -4884,15 +4732,13 @@ protected override bool ProcessDialogKey(Keys keyData) if ((keyData & (Keys.Alt | Keys.Control)) == Keys.None) { Keys keyCode = keyData & Keys.KeyCode; - IButtonControl? button; switch (keyCode) { case Keys.Return: - button = (IButtonControl?)Properties.GetObject(s_propDefaultButton); - if (button is not null) + if (Properties.TryGetValue(s_propDefaultButton, out IButtonControl? button)) { - // PerformClick now checks for validationcancelled... + // PerformClick now checks for validationcancelled. if (button is Control) { button.PerformClick(); @@ -4903,8 +4749,7 @@ protected override bool ProcessDialogKey(Keys keyData) break; case Keys.Escape: - button = (IButtonControl?)Properties.GetObject(s_propCancelButton); - if (button is not null) + if (Properties.TryGetValue(s_propCancelButton, out button)) { // In order to keep the behavior in sync with native // and MFC dialogs, we want to not give the cancel button @@ -4997,14 +4842,12 @@ internal void RaiseFormClosedOnAppExit() { // Fire FormClosed event on all the forms that this form owns and are not in the Application.OpenForms collection // This is to be consistent with what WmClose does. - int ownedFormsCount = Properties.GetValueOrDefault(s_propOwnedFormsCount); - if (ownedFormsCount > 0) + if (Properties.TryGetValue(s_propOwnedForms, out List? ownedForms)) { - Form[] ownedForms = OwnedForms; FormClosedEventArgs fce = new(CloseReason.FormOwnerClosing); - for (int i = ownedFormsCount - 1; i >= 0; i--) + for (int i = ownedForms.Count - 1; i >= 0; i--) { - if (ownedForms[i] is not null && !Application.OpenForms.Contains(ownedForms[i])) + if (!Application.OpenForms.Contains(ownedForms[i])) { ownedForms[i].OnFormClosed(fce); } @@ -5027,12 +4870,10 @@ internal bool RaiseFormClosingOnAppExit() { // Fire FormClosing event on all the forms that this form owns and are not in the Application.OpenForms collection // This is to be consistent with what WmClose does. - int ownedFormsCount = Properties.GetValueOrDefault(s_propOwnedFormsCount); - if (ownedFormsCount > 0) + if (Properties.TryGetValue(s_propOwnedForms, out List? ownedForms)) { - Form[] ownedForms = OwnedForms; FormClosingEventArgs fce = new(CloseReason.FormOwnerClosing, false); - for (int i = ownedFormsCount - 1; i >= 0; i--) + for (int i = ownedForms.Count - 1; i >= 0; i--) { if (ownedForms[i] is not null && !Application.OpenForms.Contains(ownedForms[i])) { @@ -5124,34 +4965,14 @@ public void RemoveOwnedForm(Form? ownedForm) if (ownedForm.OwnerInternal is not null) { - ownedForm.Owner = null; // NOTE: this will call RemoveOwnedForm again, bypassing if. + // NOTE: this will call RemoveOwnedForm again, bypassing if. + ownedForm.Owner = null; return; } - Form?[]? ownedForms = Properties.GetValueOrDefault(s_propOwnedForms); - int ownedFormsCount = Properties.GetValueOrDefault(s_propOwnedFormsCount); - - if (ownedForms is not null) + if (Properties.TryGetValue(s_propOwnedForms, out List? ownedForms)) { - for (int i = 0; i < ownedFormsCount; i++) - { - if (ownedForm.Equals(ownedForms[i])) - { - // clear out the reference. - ownedForms[i] = null; - - // compact the array. - if (i + 1 < ownedFormsCount) - { - Array.Copy(ownedForms, i + 1, ownedForms, i, ownedFormsCount - i - 1); - ownedForms[ownedFormsCount - 1] = null; - } - - ownedFormsCount--; - } - } - - Properties.AddValue(s_propOwnedFormsCount, ownedFormsCount); + ownedForms.Remove(ownedForm); } } @@ -5161,11 +4982,8 @@ public void RemoveOwnedForm(Form? ownedForm) private void ResetIcon() { _icon = null; - if (_smallIcon is not null) - { - _smallIcon.Dispose(); - _smallIcon = null; - } + _smallIcon?.Dispose(); + _smallIcon = null; _formState[s_formStateIconSet] = 0; UpdateWindowIcon(true); @@ -5174,10 +4992,7 @@ private void ResetIcon() /// /// Resets the TransparencyKey to Color.Empty. /// - private void ResetTransparencyKey() - { - TransparencyKey = Color.Empty; - } + private void ResetTransparencyKey() => TransparencyKey = Color.Empty; /// /// Occurs when the form enters the sizing modal loop @@ -5489,13 +5304,13 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound /// private void SetDefaultButton(IButtonControl? button) { - IButtonControl? defaultButton = (IButtonControl?)Properties.GetObject(s_propDefaultButton); + IButtonControl? existing = Properties.GetValueOrDefault(s_propDefaultButton); - if (defaultButton != button) + if (existing != button) { - defaultButton?.NotifyDefault(false); + existing?.NotifyDefault(false); - Properties.SetObject(s_propDefaultButton, button); + Properties.AddOrRemoveValue(s_propDefaultButton, button); button?.NotifyDefault(true); } } @@ -5629,7 +5444,7 @@ public void Show(IWin32Window? owner) HWND activeHwnd = PInvoke.GetActiveWindow(); HandleRef ownerHwnd = owner is null ? GetHandleRef(activeHwnd) : GetSafeHandle(owner); - Properties.SetObject(s_propDialogOwner, owner); + Properties.AddOrRemoveValue(s_propDialogOwner, owner); Form? oldOwner = OwnerInternal; if (owner is Form ownerForm && owner != oldOwner) { @@ -5877,7 +5692,7 @@ public DialogResult ShowDialog(IWin32Window? owner) // the window may never receive Dpi changed event even if its parent has different Dpi. // Users at runtime, has to move the window between the screens to get the Dpi changed events triggered. - Properties.SetObject(s_propDialogOwner, owner); + Properties.AddOrRemoveValue(s_propDialogOwner, owner); if (owner is Form form && owner != oldOwner) { Owner = form; @@ -5938,7 +5753,7 @@ public DialogResult ShowDialog(IWin32Window? owner) finally { Owner = oldOwner; - Properties.SetObject(s_propDialogOwner, null); + Properties.RemoveValue(s_propDialogOwner); GC.KeepAlive(ownerHwnd.Wrapper); } @@ -6844,16 +6659,16 @@ private void WmClose(ref Message m) } // Always fire OnClosing irrespectively of the validation result - // Pass the validation result into the EventArgs... + // Pass the validation result into the EventArgs. // Call OnClosing/OnFormClosing on all the forms that current form owns. - Form[] ownedForms = OwnedForms; - int ownedFormsCount = Properties.GetValueOrDefault(s_propOwnedFormsCount); - for (int i = ownedFormsCount - 1; i >= 0; i--) + + if (Properties.TryGetValue(s_propOwnedForms, out List? ownedForms)) { - FormClosingEventArgs cfe = new(CloseReason.FormOwnerClosing, e.Cancel); - if (ownedForms[i] is not null) + for (int i = ownedForms.Count - 1; i >= 0; i--) { + FormClosingEventArgs cfe = new(CloseReason.FormOwnerClosing, e.Cancel); + // Call OnFormClosing on the child forms. ownedForms[i].OnFormClosing(cfe); if (cfe.Cancel) @@ -6917,13 +6732,11 @@ private void WmClose(ref Message m) } // Call OnClosed/OnFormClosed on all the forms that current form owns. - Form[] ownedForms = OwnedForms; - int ownedFormsCount = Properties.GetValueOrDefault(s_propOwnedFormsCount); - for (int i = ownedFormsCount - 1; i >= 0; i--) + if (Properties.TryGetValue(s_propOwnedForms, out List? ownedForms)) { - fc = new FormClosedEventArgs(CloseReason.FormOwnerClosing); - if (ownedForms[i] is not null) + for (int i = ownedForms.Count - 1; i >= 0; i--) { + fc = new FormClosedEventArgs(CloseReason.FormOwnerClosing); // Call OnClosed and OnFormClosed on the child forms. #pragma warning disable WFDEV004 // Type or member is obsolete - compat ownedForms[i].OnClosed(fc); @@ -7053,12 +6866,10 @@ private unsafe void WmGetMinMaxInfoHelper(ref Message m, Size minTrack, Size max private void WmMdiActivate(ref Message m) { base.WndProc(ref m); - Debug.Assert(Properties.ContainsObjectThatIsNotNull(s_propFormMdiParent), "how is formMdiParent null?"); + Debug.Assert(Properties.ContainsKey(s_propFormMdiParent), "how is formMdiParent null?"); Debug.Assert(IsHandleCreated, "how is handle 0?"); - Form? formMdiParent = (Form?)Properties.GetObject(s_propFormMdiParent); - - if (formMdiParent is not null) + if (Properties.TryGetValue(s_propFormMdiParent, out Form? formMdiParent)) { // This message is propagated twice by the MDIClient window. Once to the // window being deactivated and once to the window being activated. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/Containers/ContainerControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/Containers/ContainerControl.cs index c135b332ded..5c9351a7141 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/Containers/ContainerControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/Containers/ContainerControl.cs @@ -575,10 +575,7 @@ private bool AssignActiveControlInternal(Control? value) /// Used to notify the AxContainer that the form has been created. This should only be called /// if there is an AX container. /// - private void AxContainerFormCreated() - { - ((AxHost.AxContainer?)Properties.GetObject(s_propAxContainer))?.FormCreated(); - } + private void AxContainerFormCreated() => Properties.GetValueOrDefault(s_propAxContainer)?.FormCreated(); /// /// Specifies whether this control can process the mnemonic or not. @@ -587,14 +584,12 @@ private void AxContainerFormCreated() internal AxHost.AxContainer CreateAxContainer() { - object? aXContainer = Properties.GetObject(s_propAxContainer); - if (aXContainer is null) + if (!Properties.TryGetValue(s_propAxContainer, out AxHost.AxContainer? container)) { - aXContainer = new AxHost.AxContainer(this); - Properties.SetObject(s_propAxContainer, aXContainer); + container = Properties.AddValue(s_propAxContainer, new AxHost.AxContainer(this)); } - return (AxHost.AxContainer)aXContainer; + return container; } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DefaultLayout.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DefaultLayout.cs index e840c5ea1d7..27f18a76b46 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DefaultLayout.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DefaultLayout.cs @@ -1002,10 +1002,9 @@ public static void ScaleAnchorInfo(IArrangedElement element, SizeF factor) private static Rectangle GetCachedBounds(IArrangedElement element) { - if (element.Container is not null) + if (element.Container is { } container) { - IDictionary? dictionary = (IDictionary?)element.Container.Properties.GetObject(s_cachedBoundsProperty); - if (dictionary is not null) + if (container.Properties.TryGetValue(s_cachedBoundsProperty, out IDictionary? dictionary)) { object? bounds = dictionary[element]; if (bounds is not null) @@ -1018,10 +1017,8 @@ private static Rectangle GetCachedBounds(IArrangedElement element) return element.Bounds; } - private static bool HasCachedBounds(IArrangedElement? container) - { - return container is not null && container.Properties.ContainsObjectThatIsNotNull(s_cachedBoundsProperty); - } + private static bool HasCachedBounds(IArrangedElement? container) => + container is not null && container.Properties.ContainsKey(s_cachedBoundsProperty); private static void ApplyCachedBounds(IArrangedElement container) { @@ -1036,68 +1033,60 @@ private static void ApplyCachedBounds(IArrangedElement container) } } - IDictionary? dictionary = (IDictionary?)container.Properties.GetObject(s_cachedBoundsProperty); - if (dictionary is not null) + if (!container.Properties.TryGetValue(s_cachedBoundsProperty, out IDictionary? dictionary)) { + return; + } + #if DEBUG - // In debug builds, we need to modify the collection, so we add a break and an - // outer loop to prevent attempting to IEnumerator.MoveNext() on a modified - // collection. - while (dictionary.Count > 0) - { + // In debug builds, we need to modify the collection, so we add a break and an + // outer loop to prevent attempting to IEnumerator.MoveNext() on a modified + // collection. + while (dictionary.Count > 0) + { #endif - foreach (DictionaryEntry entry in dictionary) - { - IArrangedElement element = (IArrangedElement)entry.Key; + foreach (DictionaryEntry entry in dictionary) + { + IArrangedElement element = (IArrangedElement)entry.Key; - Debug.Assert(element.Container == container, "We have non-children in our containers cached bounds store."); + Debug.Assert(element.Container == container, "We have non-children in our containers cached bounds store."); #if DEBUG - // We are about to set the bounds to the cached value. We clear the cached value - // before SetBounds because some controls fiddle with the bounds on SetBounds - // and will callback InitLayout with a different bounds and BoundsSpecified. - dictionary.Remove(entry.Key); + // We are about to set the bounds to the cached value. We clear the cached value + // before SetBounds because some controls fiddle with the bounds on SetBounds + // and will callback InitLayout with a different bounds and BoundsSpecified. + dictionary.Remove(entry.Key); #endif - Rectangle bounds = (Rectangle)entry.Value!; - element.SetBounds(bounds, BoundsSpecified.None); + Rectangle bounds = (Rectangle)entry.Value!; + element.SetBounds(bounds, BoundsSpecified.None); #if DEBUG - break; - } -#endif + break; } - - ClearCachedBounds(container); +#endif } - } - private static void ClearCachedBounds(IArrangedElement container) - { - container.Properties.SetObject(s_cachedBoundsProperty, null); + ClearCachedBounds(container); } + private static void ClearCachedBounds(IArrangedElement container) => container.Properties.RemoveValue(s_cachedBoundsProperty); + private static void SetCachedBounds(IArrangedElement element, Rectangle bounds) { - if (bounds != GetCachedBounds(element)) + if (element.Container is { } container && bounds != GetCachedBounds(element)) { - IDictionary? dictionary = (IDictionary?)element.Container!.Properties.GetObject(s_cachedBoundsProperty); - if (dictionary is null) + if (!container.Properties.TryGetValue(s_cachedBoundsProperty, out IDictionary? dictionary)) { - dictionary = new HybridDictionary(); - element.Container.Properties.SetObject(s_cachedBoundsProperty, dictionary); + dictionary = container.Properties.AddValue(s_cachedBoundsProperty, new HybridDictionary()); } dictionary[element] = bounds; } } - internal static AnchorInfo? GetAnchorInfo(IArrangedElement element) - { - return (AnchorInfo?)element.Properties.GetObject(s_layoutInfoProperty); - } + internal static AnchorInfo? GetAnchorInfo(IArrangedElement element) => + element.Properties.GetValueOrDefault(s_layoutInfoProperty); - internal static void SetAnchorInfo(IArrangedElement element, AnchorInfo? value) - { - element.Properties.SetObject(s_layoutInfoProperty, value); - } + internal static void SetAnchorInfo(IArrangedElement element, AnchorInfo? value) => + element.Properties.AddOrRemoveValue(s_layoutInfoProperty, value); private protected override void InitLayoutCore(IArrangedElement element, BoundsSpecified specified) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/TableLayout.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/TableLayout.cs index bfe06db7dff..37e3d6942d6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/TableLayout.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/TableLayout.cs @@ -1350,8 +1350,7 @@ internal static TableLayoutPanelCellPosition GetPositionFromControl(IArrangedEle internal static LayoutInfo GetLayoutInfo(IArrangedElement element) { - LayoutInfo? layoutInfo = (LayoutInfo?)element.Properties.GetObject(s_layoutInfoProperty); - if (layoutInfo is null) + if (!element.Properties.TryGetValue(s_layoutInfoProperty, out LayoutInfo? layoutInfo)) { layoutInfo = new LayoutInfo(element); SetLayoutInfo(element, layoutInfo); @@ -1362,7 +1361,7 @@ internal static LayoutInfo GetLayoutInfo(IArrangedElement element) internal static void SetLayoutInfo(IArrangedElement element, LayoutInfo value) { - element.Properties.SetObject(s_layoutInfoProperty, value); + element.Properties.AddOrRemoveValue(s_layoutInfoProperty, value); Debug.Assert(GetLayoutInfo(element) == value, "GetLayoutInfo should return the same value as we set it to"); } @@ -1376,11 +1375,9 @@ internal static void SetLayoutInfo(IArrangedElement element, LayoutInfo value) // store. internal static ContainerInfo GetContainerInfo(IArrangedElement container) { - ContainerInfo? containerInfo = (ContainerInfo?)container.Properties.GetObject(s_containerInfoProperty); - if (containerInfo is null) + if (!container.Properties.TryGetValue(s_containerInfoProperty, out ContainerInfo? containerInfo)) { - containerInfo = new ContainerInfo(container); - container.Properties.SetObject(s_containerInfoProperty, containerInfo); + containerInfo = container.Properties.AddValue(s_containerInfoProperty, new ContainerInfo(container)); } return containerInfo; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyStore.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyStore.cs index 8a8bc28447d..a0ed64e0392 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyStore.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyStore.cs @@ -25,14 +25,6 @@ internal class PropertyStore /// public static int CreateKey() => s_currentKey++; - // REMOVE - /// - /// Retrieves an object value from our property list. - /// This will set value to null and return false if the - /// list does not contain the given key. - /// - public object? GetObject(int key) => GetObject(key, out _); - // REMOVE /// /// Retrieves an object value from our property list. @@ -211,7 +203,8 @@ public string AddOrRemoveString(int key, string? value) /// /// Adds the given value to the store. /// - public void AddValue(int key, T value) + [return: NotNullIfNotNull(nameof(value))] + public T AddValue(int key, T value) { // For value types that are larger than 8 bytes, we attempt to update the existing value // to avoid another boxing allocation. @@ -228,6 +221,8 @@ public void AddValue(int key, T value) { _values[key] = Value.Create(value); } + + return value; } private unsafe void AddOrUpdate(int key, T value) where T : unmanaged diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripItemTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripItemTests.cs index a47a12f8c91..ee840a48e71 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripItemTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripItemTests.cs @@ -282,7 +282,6 @@ public void ToolStripItem_Ctor_String_Image_EventHandler_String_InvokeClick_Call public static IEnumerable AccessibilityObject_Get_TestData() { - yield return new object[] { null }; yield return new object[] { new AccessibleObject() }; yield return new object[] { new SubToolStripItem.ToolStripItemAccessibleObject(new SubToolStripItem()) }; } @@ -15648,7 +15647,7 @@ public ToolStripDropDownItemWithAccessibleObjectFieldAccessor() : base() { } public bool IsAccessibleObjectCleared() { var key = this.TestAccessor().Dynamic.s_accessibilityProperty; - return Properties.GetObject(key) is not AccessibleObject; + return !Properties.ContainsKey(key); } } }